介绍:运行在 ubuntu linux 系统,需要先打开一个终端运行服务端代码,这时,可以打开多
个终端同时运行多个客户端代码(注意客户端数目要小于 MAX_FD);在客户端输入数据后
回车,可以看见服务器收到数据,并回复客户端确认信息,客户端输入:exit,按回车,该
客户端关闭,在服务器端显示退出信息;所有客户端关闭后,服务器不会自动关闭,需要按
ctrl+c 强制关闭。
服务器端代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#define SERV_PORT 8888
#define SERV_IP "127.0.0.1" //本地回环接口
#define LIST 20 //服务器最大接受连接
#define MAX_FD 10 //FD_SET 支持描述符数量
int main(void)
{
int sockfd;
int err;
int i;
int connfd; int fd_all[MAX_FD]; //保存所有描述符,用于 select 调用后,
判断哪个可读
//下面两个备份原因是 select 调用后,会发生变化,再次调用 select 前,需要重新赋值
fd_set fd_read; //FD_SET 数据备份
评论0