select函数实现I/O复用的回声服务器

select函数可以将多个文件描述符集中到一起统一监视。
1.是否存在套接字接收数据
2.是否传输无阻塞数据
3.是否发生异常
文件描述符集中到一起需要fd_set数据执行,该数组是存有0和1的数组。
在fd_set里面注册或更改的操作都是由以下宏完成的。
FD_ZERO(fd_set *fdset):将fd_set变量的所有位初始化为0.
FD_SET(int fd,fd_set * fdset):从参数fdset指向的变量中注册文件描述符fd的信息
FD_CLR(int fd,fd_set * fdset):从参数fdset指向的变量中清除文件描述符fd的信息
FD_ISSET(int fd,fd_set * fdset):若参数fdset指向的变量中包含文件描述符fd的信息则返回true

下面是在Linux下select 实现回升服务器的server

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<sys/time.h>
#include<sys/select.h>

#define BUF_SIZE (1024)
void error_handling(const char *message);

int main(int argc,char *argv[]){
	int serv_sock,clnt_sock;
	struct sockaddr_in serv_adr,clnt_adr;
	struct timeval timeout;
	fd_set reads,cpy_reads;

	socklen_t adr_sz;
	int fd_max,str_len,fd_num,i;
	char buf[BUF_SIZE];
	if(argc != 2){
		printf("Usage:%s <Port>\n",argv[0]);
		exit(1);
	}

	serv_sock = socket(PF_INET,SOCK_STREAM,0);
	memset(&serv_adr,0,sizeof(serv_adr));
	serv_adr.sin_family = AF_INET;
	serv_adr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_adr.sin_port = htons(atoi(argv[1]));

	if(bind(serv_sock,(struct sockaddr*) &serv_adr,sizeof(serv_adr)) == -1)
		error_handling("bind() error");
	if(listen(serv_sock,5) == -1)
		error_handling("listen() error");

	FD_ZERO(&reads);
	FD_SET(serv_sock,&reads);
	fd_max = serv_sock;
	while(true){
		cpy_reads = reads;
		timeout.tv_sec = 5;
		timeout.tv_usec = 5000;

		if((fd_num = select(fd_max+1,&cpy_reads,0,0,&timeout)) == -1)
			break;
		if(fd_num == 0)
			continue;

		for(i=0;i<fd_max+1;++i){
			if(FD_ISSET(i,&cpy_reads)){
				if(i == serv_sock){
					adr_sz = sizeof(clnt_adr);
					clnt_sock = accept(serv_sock,(struct sockaddr*) &clnt_adr,&adr_sz);
					FD_SET(clnt_sock,&reads);
					if(fd_max < clnt_sock)
						fd_max = clnt_sock;
					printf("Connected client:%d\n",clnt_sock);
				}
				else{
					str_len = read(i,buf,BUF_SIZE);
					if(str_len == 0){
						FD_CLR(i,&reads);
						close(i);
						printf("closed client:%d\n",i);
					}
					else{
						write(i,buf,str_len);
					}
				}
			}
		}
	}
	close(serv_sock);
	return 0;
}
void error_handling(const char *message){
	fputs(message,stderr);
	fputc('\n',stderr);
	exit(1);
}

Linux下的echo_client

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>

#define BUF_SIZE (1024)
void error_handling(const char *message);

int main(int argc,char *argv[]){
	int sock;
	char message[BUF_SIZE];
	int str_len;
	struct sockaddr_in serv_addr;

	if(argc != 3){
		printf("Usage :%s <IP> <Port>\n",argv[0]);
		exit(1);
	}

	sock = socket(PF_INET,SOCK_STREAM,0);
	if(sock == -1)
		error_handling("socket() error");

	memset(&serv_addr,0,sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
	serv_addr.sin_port = htons(atoi(argv[2]));

	if(connect(sock,(struct sockaddr*) &serv_addr,sizeof(serv_addr)) == -1)
		error_handling("connect() error");
	else
		puts("Connected........");
	while(true){
		fputs("Input message(Q to quit):",stdout);
		fgets(message,BUF_SIZE,stdin);

		if(!strcmp(message,"q\n") || !strcmp(message,"Q\n"))
			break;
		write(sock,message,strlen(message));
		str_len = read(sock,message,BUF_SIZE-1);
		message[str_len] = 0;
		printf("Message from server:%s",message);
	}
	close(sock);
	return 0;
}

void error_handling(const char *message){
	fputs(message,stderr);
	fputc('\n',stderr);
	exit(1);
}

windows下的echo_client

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

#define BUF_SIZE (1024)
void ErrorHandling(const char* message);

int main(int argc, char* argv[]) {
	WSADATA wsaData;
	SOCKET hSocket;
	char buf[BUF_SIZE];
	int str_len;
	SOCKADDR_IN servAdr;
	if (argc != 3) {
		printf("Usage:%s <IP> <Port>\n", argv[0]);
		exit(1);
	}
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
		ErrorHandling("WSAStartup() error");
	hSocket = socket(PF_INET, SOCK_STREAM, 0);
	if (hSocket == INVALID_SOCKET)
		ErrorHandling("socket() error");
	memset(&servAdr, 0, sizeof(servAdr));
	servAdr.sin_family = AF_INET;
	servAdr.sin_addr.s_addr = inet_addr(argv[1]);
	servAdr.sin_port = htons(atoi(argv[2]));

	if (connect(hSocket, (SOCKADDR*)& servAdr, sizeof(servAdr)) == SOCKET_ERROR)
		ErrorHandling("connect() error!");
	else
		puts("connected....");

	while (true) {
		fputs("Input message(Q to quit):", stdout);
		fgets(buf, BUF_SIZE, stdin);
		if (!strcmp(buf, "q\n") || !strcmp(buf, "Q\n"))
			break;
		send(hSocket, buf, strlen(buf), 0);
		str_len = recv(hSocket, buf, BUF_SIZE - 1, 0);
		buf[str_len] = 0;
		printf("message from server:%s\n", buf);
	}
	closesocket(hSocket);
	WSACleanup();
	return 0;
}
void ErrorHandling(const char* message) {
	fputs(message, stderr);
	fputc('\n', stderr);
	exit(1);
}
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页