欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

回复 tcp socket通信例子

程序员文章站 2022-04-24 13:26:35
...

回复 http://www.oschina.net/code/snippet_102078_2670  tcp socket通信例子

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <errno.h>
#include <error.h>

#include <string.h>
#include <stdio.h>

#include <locale.h>

#define socket_error(status, name) if (status == -1) { \
	printf("ERROR: %d\n",errno); \
	error(-1, errno, "%s", name); \
}

int main(int argc, char **argv)
{
	int  status  = 0; 

	int                server;       
	struct sockaddr_in server_addr;  

	int                client;
	struct sockaddr_in client_addr;
	socklen_t          client_addr_len = sizeof(client_addr);

	/* fdsets */
	fd_set all_fds;
	fd_set read_fds;
	int    fd_max   = 0;
	int    fd_cur   = 0;
	int    fd_count = 0;


	setlocale(LC_ALL, "zh_CN.UTF-8");

	server = socket(PF_INET, SOCK_STREAM, 0); 
	socket_error(status, "server");

	/* 允许重新使用地址 */
	int reuseaddr = 1;
	status = setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
	socket_error(status, "setsockopt so_reuseaddr");

	server_addr.sin_family      = AF_INET; 
	server_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); 
	server_addr.sin_port        = htons(9090); 

	status = bind(server, (struct sockaddr*)&server_addr, sizeof(server_addr));
	socket_error(status, "bind");

	status = listen(server, 50);
	socket_error(status, "listen");

	/* 初使化all_fdsfds */
	FD_ZERO(&all_fds);

	/* 加入server到all_fds */
	FD_SET(server, &all_fds);

	/* 当前最大的描述符均为server */
	fd_max = server;
	while (1) {
		read_fds = all_fds;
		fd_count = select(fd_max+1, &read_fds, NULL, NULL, NULL);
		socket_error(fd_count, "select");

		int i=0;
		for (i=0; i < fd_max+1; ++i) {
			fd_cur = i;

			/* fd_cur没有处于read状态则跳过 */
			if (!FD_ISSET(fd_cur, &read_fds))
				continue;

			if (fd_cur == server ) {
				client = accept(server, (struct sockaddr*)&client_addr, &client_addr_len);
				socket_error(client, "accept");

				printf("%s connected\n", inet_ntoa(client_addr.sin_addr));

				/* 加入client到all_fds */
				FD_SET(client, &all_fds);
				if (client>fd_max)
					fd_max = client;

			} else {
				/* 客户端为fd_cur */
				client = fd_cur;

				/* Socket 相关操作 */

				/* 从all_fds中删除client并关闭client */
				FD_CLR(client, &all_fds);
				close(client);
			} 
		}

	}
	return 0;
}

转载于:https://my.oschina.net/jiangmiao/blog/11717