linuxC编写的基于TCP的网络聊天室源代码
谁那里有linux C编写的基于TCP的网络聊天室 源代码,共享一下! 谢谢啦!
#include <errno.h> #include <string.h> #include <stdio.h> #include <strings.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define SERV_IPADDR "192.168.1.89" #define SERV_PORT 6000 #define QUIT_STR "quit" int main(void) { int fd = -1; int ret = -1; struct sockaddr_in sin; fd = socket(AF_INET, SOCK_STREAM, 0); if(fd < 0) { perror("socket error"); return -1; } sin.sin_family = AF_INET; sin.sin_port = htons(SERV_PORT); sin.sin_addr.s_addr = inet_addr(SERV_IPADDR); do { ret = connect(fd, (struct sockaddr *)&sin, sizeof(sin)); }while(ret < 0 && EINTR == errno); if(ret < 0) { perror("connect error"); exit(1); } char buf[BUFSIZ]; while(1) { bzero(buf, BUFSIZ); printf("Input string:\n"); fgets(buf, BUFSIZ-1, stdin); buf[BUFSIZ-1] = '\0'; ret = write(fd, buf, strlen(buf)); if( ret < 0) { perror("write error"); continue; } if(!strncasecmp(buf, QUIT_STR,strlen(QUIT_STR))) { printf("Client exiting.\n"); break; } } close(fd); return 0; }
服务器
C/C++ code?#include <errno.h> #include <string.h> #include <stdio.h> #include <strings.h> #include <unistd.h> #include <sys/types.h> /* See NOTES */ #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define SERV_IPADDR "192.168.1.89" #define SERV_PORT 6000 #define BACKLOG 5 #define QUIT_STR "quit" int main(void) { int fd = -1, newfd = -1; struct sockaddr_in sin; struct sockaddr_in cin; socklen_t addrlen = -1; /* 1.建立socket fd*/ fd = socket(AF_INET, SOCK_STREAM, 0); if(fd < 0) { perror("socket error"); return -1; } /*1.1 改变套接字的缺省属性 */ int b_on = 1; setsockopt(fd, SOL_SOCKET,SO_REUSEADDR, &b_on, sizeof(int)); //2.填充sin sin.sin_family = AF_INET; sin.sin_port = htons(SERV_PORT); sin.sin_addr.s_addr = inet_addr(SERV_IPADDR); //memset(sin.sin_zero, 0, 8); bzero(sin.sin_zero, 8); //3. 绑定 if( bind(fd, (struct sockaddr *)&sin, sizeof(sin))) { perror("bind error"); return -1; } //4. 把主动套接字设置成被动套接字 listen(fd, 5); printf("Server started.\n"); addrlen = sizeof(cin); do { newfd = accept(fd, (struct sockaddr *)&cin, &addrlen); }while(newfd < 0 && EINTR == errno); if(newfd < 0) { perror("accept error"); return -1; } char cli_dot_addr[16]; bzero(cli_dot_addr, 16); inet_ntop(AF_INET, (void *)&cin.sin_addr.s_addr, cli_dot_addr, sizeof(cli_dot_addr)); printf("Client info,Ipaddr:%s, port:%d\n",cli_dot_addr, ntohs(cin.sin_port)); #endif int ret = -1; char buf[BUFSIZ]; while(1) { bzero(buf, BUFSIZ); do { ret = read(newfd,buf, BUFSIZ-1); //阻塞 } while(ret < 0 && EINTR == errno); if( ret < 0) { perror("read error"); continue; } // buf[BUFSIZ-1] = '\0'; printf("Server receive:%s\n", buf); if(!ret || !strncasecmp(buf, QUIT_STR, strlen(QUIT_STR))) { printf("Server: Client exited.\n"); close(newfd); break; } } close(fd); return 0; }