Linux下基于Socket网络通信的多人聊天室
Posted yyb123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux下基于Socket网络通信的多人聊天室相关的知识,希望对你有一定的参考价值。
服务端
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <arpa/inet.h> #include <netinet/in.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> char* nam[50]; int count = 0; int cfd[50]; int clifd = 0; void* pthread_chat(void* arg) { int *p = arg; int n = *p; while(1) { char buf[255] = {}; if (-1 == recv(cfd[n],buf,sizeof(buf),0)) { close(cfd[n]); cfd[n] = 0; break; } for (int i = 0; i < count+1; ++i) { if (cfd[i] != 0) { send(cfd[i],buf,sizeof(buf),0); } } } } int main(int argc,char* argv[]) { int sockfd = socket(AF_INET,SOCK_STREAM,0); if (0 > sockfd) { perror("socket"); return -1; } struct sockaddr_in addr = {AF_INET}; addr.sin_port = htons(5566); addr.sin_addr.s_addr = inet_addr("192.168.2.120"); int ret = bind(sockfd,(struct sockaddr*)&addr,sizeof(addr)); if (0 > ret) { perror("bind"); return -1; } listen(sockfd,1024); struct sockaddr_in src_addr = {}; socklen_t addr_len = sizeof(src_addr); while(1) { clifd = accept(sockfd,(struct sockaddr*)&src_addr,&addr_len); int flag = 0; while(clifd != 0) { for (int i = 0; i < count+1; ++i) { if(cfd[count] == 0) { flag = 1; cfd[count] = clifd; pthread_t ptid; pthread_create(&ptid,NULL,pthread_chat,&count); } } if (flag == 0) { cfd[++count] = clifd; pthread_t ptid; pthread_create(&ptid,NULL,pthread_chat,&count); } clifd = 0; } } close(sockfd); }
客户端
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <arpa/inet.h> #include <netinet/in.h> #include <stdlib.h> #include <unistd.h> int main(int argc,char* argv[]) { int sockfd = socket(AF_INET,SOCK_STREAM,0); if (0 > sockfd) { perror("socket"); return -1; } struct sockaddr_in addr = {AF_INET}; addr.sin_port = htons(atoi(argv[1])); addr.sin_addr.s_addr = inet_addr(argv[2]); int ret = connect(sockfd,(struct sockaddr*)&addr,sizeof(addr)); if (0 > ret) { perror("connect"); return -1; } if (fork() == 0) { while(1) { char buf[255] = {}; recv(sockfd,buf,sizeof(buf),0); printf("%s ",buf); } } while(1) { char buf[255] = {}; char data[255] = {}; gets(data); sprintf(buf,"%s:%s",argv[3],data); send(sockfd,buf,strlen(buf),0); } close(sockfd); }
以上是关于Linux下基于Socket网络通信的多人聊天室的主要内容,如果未能解决你的问题,请参考以下文章