简单实例1
server.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> #include <pthread.h> int sockfd;//服务器socket ];//客户端的socketfd,100个元素,fds[0]~fds[99] ;//用来控制进入聊天室的人数为100以内 char* IP = "0.0.0.0"; ; typedef struct sockaddr SA; void init(){ sockfd = socket(PF_INET,SOCK_STREAM,); ){ perror("创建socket失败"); exit(-); } struct sockaddr_in addr; addr.sin_family = PF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = inet_addr(IP); ){ perror("绑定失败"); exit(-); } ) == -){ perror("设置监听失败"); exit(-); } } void SendMsgToAll(char* msg){ int i; ;i < size;i++){ ){ printf("sendto%d\n",fds[i]); send(fds[i],msg,strlen(msg),); } } } void* service_thread(void* p){ int fd = *(int*)p; printf("pthread = %d\n",fd); ){ ] = {}; ) <= ){ int i; ;i < size;i++){ if (fd == fds[i]){ fds[i] = ; break; } } printf("退出:fd = %dquit\n",fd); pthread_exit((void*)i); } //把服务器接受到的信息发给所有的客户端 SendMsgToAll(buf); } } void service(){ printf("服务器启动\n"); ){ struct sockaddr_in fromaddr; socklen_t len = sizeof(fromaddr); int fd = accept(sockfd,(SA*)&fromaddr,&len); ){ printf("客户端连接出错...\n"); continue; } ; ;i < size;i++){ ){ //记录客户端的socket fds[i] = fd; printf("fd = %d\n",fd); //有客户端连接之后,启动线程给此客户服务 pthread_t tid; pthread_create(&tid,,service_thread,&fd); break; } if (size == i){ //发送给客户端说聊天室满了 char* str = "对不起,聊天室已经满了!"; send(fd,str,strlen(str),); close(fd); } } } } int main(){ init(); service(); }
client.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <pthread.h> int sockfd;//客户端socket char* IP = "192.168.1.105";//服务器的IP ;//服务器服务端口 typedef struct sockaddr SA; ]; void init(){ sockfd = socket(PF_INET,SOCK_STREAM,); struct sockaddr_in addr; addr.sin_family = PF_INET; addr.sin_port = htons(PORT); addr.sin_addr.s_addr = inet_addr(IP); ){ perror("无法连接到服务器"); exit(-); } printf("客户端启动成功\n"); } void start(){ pthread_t id; void* recv_thread(void*); pthread_create(&id,,recv_thread,); ] = {}; sprintf(buf2,"%s进入了聊天室",name); send(sockfd,buf2,strlen(buf2),); ){ ] = {}; scanf("%s",buf); ] = {}; sprintf(msg,"%s:%s",name,buf); send(sockfd,msg,strlen(msg),); ){ memset(buf2,,sizeof(buf2)); sprintf(buf2,"%s退出了聊天室",name); send(sockfd,buf2,strlen(buf2),); break; } } close(sockfd); } void* recv_thread(void* p){ ){ ] = {}; ) <= ){ return; } printf("%s\n",buf); } } int main(){ init(); printf("请输入您的名字:"); scanf("%s",name); start(); ; }