📄 chatc.c
字号:
#include <sys/types.h>#include <sys/socket.h>#include <stdio.h>#include <unistd.h>#include <netinet/in.h>#include <arpa/inet.h>#include <errno.h>#include <sys/select.h>#define MAXLINE 1024char sendhead[MAXLINE];voidstr_cli(FILE *fp, int sockfd){ int maxfdp1, stdineof; fd_set rset; char recvbuf[MAXLINE],sendbuf[MAXLINE],temp[MAXLINE]; int n,len; stdineof = 0; FD_ZERO(&rset); for ( ; ; ) { if (stdineof == 0) FD_SET(fileno(fp), &rset); FD_SET(sockfd, &rset); if(sockfd>fileno(fp)) maxfdp1=sockfd+1; else maxfdp1=fileno(fp)+1; if( ( select(maxfdp1, &rset, NULL, NULL, NULL) )<0) { perror("select"); } if (FD_ISSET(sockfd, &rset)) { /* socket is readable */ n=read(sockfd, recvbuf, MAXLINE) ; if(n<0) { if (stdineof == 1) return; /* normal termination */ else perror("str_cli: server terminated prematurely"); } fputs(recvbuf,stdout); } if (FD_ISSET(fileno(fp), &rset)) { /* input is readable */ n= MAXLINE; bzero(sendbuf,MAXLINE); if (fgets(sendbuf, MAXLINE, fp) == NULL) { stdineof = 1; shutdown(sockfd, SHUT_WR); /* send FIN */ FD_CLR(fileno(fp), &rset); continue; } strcpy(temp,sendhead); strcat(temp,sendbuf); printf("%s",temp); write(sockfd, temp, n); } }}int main(int argc , char* argv[]){int sockfd;struct sockaddr_in servaddr;char s1[]=" say:";if(argc!=4){printf("useage:client address port yourname");exit(0);} if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1 ){ perror("socket"); exit(1);} printf("%s enter the room\n",argv[3]); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(atoi(argv[2])); inet_pton(AF_INET,argv[1],&servaddr.sin_addr); if( ( connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) )<0) { perror("connect"); exit(1); } strcpy(sendhead,argv[3]); strcat(sendhead,s1); str_cli(stdin,sockfd); exit(0);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -