socket 客户端 服务器端 代码例子 | 多路IO复用 select

服务器端代码

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define DEFAULT_PORT 6666

int main(int argc, char** argv)
{
	int serverfd, acceptfd;
	struct sockaddr_in my_addr;    //服务端
	struct sockaddr_in their_addr; //客户端
	unsigned int sin_size, myport = 6666, lisnum = 10;
	if((serverfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		perror("socket");
		return -1;
	}
	printf("socket ok \n");
	my_addr.sin_family = AF_INET;
	my_addr.sin_port = htons(DEFAULT_PORT);
	//指定地址为0.0.0.0即为任意地址,内核在套接字已连接或者在套接字上发送数据时才选择本地地址
	my_addr.sin_addr.s_addr = INADDR_ANY;
	bzero(&(my_addr.sin_zero), 0);
	//将本地地址和套接字绑定
	if(bind(serverfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == -1)
	{
		perror("bind");
		return -2;
	}
	printf("bind ok \n");
	//监听服务器套接字
	if(listen(serverfd, lisnum) == -1)
	{
		perror("listen");
		return -3;
	}
	printf("listen ok \n");

	fd_set client_fdset;
	int maxsock;
	struct timeval tv;
	int client_sockfd[5];
	//客户端的套接字数组初始化为0
	bzero((void*) client_sockfd, sizeof(client_sockfd));
	int conn_amount = 0;
	maxsock = serverfd;
	char buffer[1024];
	int ret = 0;
	while(1)
	{
		//fd 集合不能复用 每次轮寻都要重新设置
		FD_ZERO(&client_fdset);
		FD_SET(serverfd, &client_fdset);//将serverfd 加入 client_fdset集合
		tv.tv_sec = 100;//设置超时时间
		tv.tv_usec = 0;
		for(int i = 0; i<5; i++)
		{
			if(client_sockfd[i]!=0)
			{
				FD_SET(client_sockfd[i], &client_fdset);
			}
		}
		//阻塞函数  直到某个IO有数据才继续往下执行
		ret = select(maxsock+1, &client_fdset, NULL, NULL, &tv);
		if(ret<0)
		{
			perror("select error!\n");
			break;
		}
		else if(ret == 0)
		{
			printf("timeout!\n");
			continue;
		}
		for(int i = 0; i

客户端代码

#include
#include
#include
#include
#include
#include
#include
#include
#include
#define DEFAULT_PORT 6666
int main(int argc, char* argv[])
{
	int connfd = 0;
	int cLen = 0;
	struct sockaddr_in client;
	if(argc<2)
	{
		printf("Uasge: clientent[server IP address]\n");
		return -1;
	}
	client.sin_family = AF_INET;
	client.sin_port = htons(DEFAULT_PORT);
	client.sin_addr.s_addr = inet_addr(argv[1]);
	connfd = socket(AF_INET, SOCK_STREAM, 0);
	if(connfd<0)
	{
		perror("socket");
		return -1;
	}
	//从客户端连向server  包含了server 的ip地址
	if(connect(connfd, (struct sockaddr*)&client, sizeof(client))<0)
	{
		perror("connect");
		return -1;
	}
	char buffer[1024];
	bzero(buffer, sizeof(buffer));
	//使用TCP从另一端接收数据 1024是缓冲区大小
	recv(connfd, buffer, 1024, 0);
	printf("recv: %s\n", buffer);
	bzero(buffer, sizeof(buffer));
	strcpy(buffer, "this is a client!\n");
	send(connfd, buffer, 1024, 0);
	while(1)
	{
		bzero(buffer, sizeof(buffer));
		scanf("%s", buffer);
		int p = strlen(buffer);
		buffer[p] = '\0';
		send(connfd, buffer, 1024, 0);
		printf("i have send buffer");
	}
	close(connfd);
	return 0;
}

 

客户端先结束连接(ctrl+c),服务器进入死循环.

你可能感兴趣的:(socket 客户端 服务器端 代码例子 | 多路IO复用 select)