1> 使用select实现tcp的服务器端,poll实现tcp的客户端(君子作业)
2> 将课堂上实现的模型重新自己实现一遍
#include<myhead.h>
#define SER_IP "192.168.124.23"
#define SER_PORT 8888 int main(int argc, const char *argv[])
{int sfd = -1;sfd=socket(AF_INET, SOCK_STREAM, 0);if(sfd == -1){perror("socket error");return -1;}printf("sfd = %d\n", sfd); //3int reuse = 1;if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse))==-1){perror("setsockopt error");return -1;}printf("端口号快速重用成功\n");struct sockaddr_in sin;sin.sin_family = AF_INET; //地址族sin.sin_port = htons(SER_PORT); //端口号sin.sin_addr.s_addr = inet_addr(SER_IP); //IP地址//2.2绑定if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin))==-1){perror("bind error");return -1;}printf("bind success\n");//3、启动监听,允许客户端连接if(listen(sfd, 128) == -1){perror("listen error");return -1;}printf("listen success\n");struct sockaddr_in cin; //用于接收客户端地址信息结构体socklen_t socklen = sizeof(cin); //用于接收客户端地址信息的大小int newfd = -1; //新创建用于通信的套接字文件描述符char sbuf[128] = ""; //从键盘上输入数据//1、创建文件描述符容器fd_set readfds, tempfds;//2、清空容器内容FD_ZERO(&readfds);//3、将sfd和0号文件描述符放入容器中FD_SET(0, &readfds);FD_SET(sfd, &readfds);int maxfd = sfd; //存放容器中最大的文件描述符的值struct sockaddr_in cin_arr[1024]; //存放客户端对应的地址信息while(1){tempfds = readfds; //将要检测的容器复制保存一份int res = select(maxfd+1, &tempfds, NULL, NULL, NULL); //阻塞等待集合中事件产生if(res == -1){perror("select error");return -1;}else if(res == 0){printf("time out\n");return -1;}for(int i=0; i<=maxfd; i++){if(!FD_ISSET(i, &tempfds)){continue;}if(i == sfd) //表示sfd触发了事件{newfd = accept(sfd, (struct sockaddr*)&cin, &socklen);if(newfd == -1){perror("accept error");return -1;}printf("newfd = %d 您有新的客户已经上线\n", newfd);printf("客户端IP:%s, 端口号为:%d\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port));FD_SET(newfd, &readfds);cin_arr[newfd] = cin; //更新一下maxfdif(newfd > maxfd){maxfd = newfd;}}else if(i == 0) {fgets(sbuf, sizeof(sbuf), stdin);sbuf[strlen(sbuf)-1] = 0;printf("触发了键盘输入事件:%s\n", sbuf);for(int k=4; k<=maxfd; k++){send(k, sbuf, strlen(sbuf), 0); }}else{char rbuf[128] = "";bzero(rbuf, sizeof(rbuf));int res = recv(i, rbuf, sizeof(rbuf), 0);if(res == 0){printf("客户端已经下线\n");close(i);FD_CLR(i, &readfds);for(int j=maxfd; j>=0; j--){if(FD_ISSET(j, &readfds)){maxfd = j;break;}}continue;}printf("[%s:%d] :%s\n", \inet_ntoa(cin_arr[i].sin_addr), ntohs(cin_arr[i].sin_port), rbuf);strcat(rbuf, "*_*");send(i, rbuf, strlen(rbuf), 0);}}}close(sfd);return 0;
}
3> 网络聊天室可以着手做了
4>思维导图