IO多路复用,解决阻塞问题
server:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #include<sys/select.h> #include<sys/time.h> #define PORT 2222 typedef struct sockaddr SA; typedef struct sockaddr_in SSA; int main() { //创建监听的套接口 int sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd < 0) { perror("socket error!\n"); exit(1); } //bind // struct sockaddr_in my_addr; struct sockaddr_in client_addr; my_addr.sin_family=AF_INET; my_addr.sin_port=htons(PORT); my_addr.sin_addr.s_addr=inet_addr("192.168.71.104"); int ret=0; if(bind(sockfd,(SA*)&my_addr,sizeof(SA))< 0) { perror("bind error!\n"); exit(1); } //listen // // if(listen(sockfd,10)< 0) { perror("listen error!\n"); exit(1); } printf("listen.......\n"); //创建新套接发送 int ssalen=sizeof(struct sockaddr_in); int nfd=accept(sockfd,(SA*)&client_addr,&ssalen); if(nfd<0) { perror("accept error!\n"); exit(1); } printf("accpet from %s\n",inet_ntoa(client_addr.sin_addr)); while(1) { //IO多路复用 fd_set st; FD_ZERO(&st); FD_SET(0,&st); FD_SET(nfd,&st); ret=select(nfd+1,&st,0,0,0); //剥夺nfd的控制权 if(FD_ISSET(nfd,&st)) { //接收数据 char buf[50]={0}; if(recv(nfd,buf,50,0)<0) { perror("recv error!\n"); exit(1); } printf("client said : %s\n",buf); } if(FD_ISSET(0,&st)) { //发送数据 char send_buf[50]={0}; memset(send_buf,0,50); ret=read(0,send_buf,50); if(ret<0) { perror("read error!\n"); exit(1); } printf("get %s\n",send_buf); if(send(nfd,send_buf,strlen(send_buf),0)<0) { perror("send error!\n"); exit(1); } printf("send is %s\n",send_buf); } } }
client:
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> #define PORT 2222 typedef struct sockaddr SA; typedef struct sockaddr_in SSA; int main() { //创建监听的套接口 int sockfd=socket(AF_INET,SOCK_STREAM,0); if(sockfd < 0) { perror("socket error!\n"); exit(1); } //建立连接 //connect struct sockaddr_in server_addr; server_addr.sin_family=AF_INET; server_addr.sin_port=htons(PORT); server_addr.sin_addr.s_addr=inet_addr("192.168.71.104"); if(connect(sockfd,(SA*)&server_addr,sizeof(server_addr)) < 0) { perror("connect error!\n"); exit(1); } printf("conncet sucess!\n"); while(1) { fd_set st; FD_ZERO(&st); FD_SET(0,&st); FD_SET(sockfd,&st); select(sockfd+1,&st,0,0,0); if(FD_ISSET(0,&st)) { //send char buf[50]={0}; int ret=read(0,buf,50); if(ret<0) { perror("read error!\n"); exit(1); } if(send(sockfd,buf,strlen(buf),0)<0) { perror("send error!\n"); exit(1); } printf("send is %s\n",buf); } //recv if(FD_ISSET(sockfd,&st)) { char recv_buf[50]={0}; if(recv(sockfd,recv_buf,50,0)<0) { perror("recv error!\n"); exit(1); } printf("server said : %s\n",recv_buf); } } }