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! "); 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! "); exit(1); } //listen // // if(listen(sockfd,10)< 0) { perror("listen error! "); exit(1); } printf("listen....... "); //创建新套接发送 int ssalen=sizeof(struct sockaddr_in); int nfd=accept(sockfd,(SA*)&client_addr,&ssalen); if(nfd<0) { perror("accept error! "); exit(1); } printf("accpet from %s ",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! "); exit(1); } printf("client said : %s ",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! "); exit(1); } printf("get %s ",send_buf); if(send(nfd,send_buf,strlen(send_buf),0)<0) { perror("send error! "); exit(1); } printf("send is %s ",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! "); 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! "); exit(1); } printf("conncet sucess! "); 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! "); exit(1); } if(send(sockfd,buf,strlen(buf),0)<0) { perror("send error! "); exit(1); } printf("send is %s ",buf); } //recv if(FD_ISSET(sockfd,&st)) { char recv_buf[50]={0}; if(recv(sockfd,recv_buf,50,0)<0) { perror("recv error! "); exit(1); } printf("server said : %s ",recv_buf); } } }