简单的linux下C编写的聊天室C-Sdemo
写一个简单的聊天室,客户端发送消息,服务端回送发的消息的长度。
1.服务端代码 tcp_server.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<unistd.h> #include<linux/in.h> #define PORT 8888 #define BACKLOG 2 //侦听队列长度 int main(int argc , char *argv[]){ int ss,sc; struct sockaddr_in server_addr; struct sockaddr_in client_addr; int err; pid_t pid; ss = socket(AF_INET,SOCK_STREAM,0); if(ss<0){ printf("socket error\n"); return -1; } bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//任意本地地址 server_addr.sin_port = htons(PORT); err = bind(ss,(struct sockaddr *)&server_addr,sizeof(server_addr)); if(err<0){ printf("bind error\n"); return -1; } err = listen(ss,BACKLOG); if(listen<0){ printf("listen error\n"); return -1; } for(;;){ int addrlen = sizeof(struct sockaddr); sc = accept(ss,(struct sockaddr *)&client_addr,&addrlen); if(sc<0){ continue; } pid = fork(); if(pid == 0){ close(ss); process_conn_server(sc); } } }
2.客户端代码 tcp_client.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> #include<sys/socket.h> #include<unistd.h> #include<linux/in.h> #define PORT 8888 int main(int argc , char *argv[]){ int s; struct sockaddr_in server_addr; int err; s = socket(AF_INET , SOCK_STREAM, 0); if(s<0){ printf("socker error\n"); return -1; } bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(PORT); inet_pton(AF_INET,argv[1],&server_addr.sin_addr); connect(s,(struct sockaddr *)&server_addr,sizeof(struct sockaddr)); process_conn_client(s); close(s); }
3.服务端与客户端操作 tcp_proccess.c
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/types.h> void process_conn_server(int s){ ssize_t size = 0; char buffer[1024]; for(;;){ size = read(s,buffer,1024); if(size == 0){ return ; } sprintf(buffer,"%d bytes altogether\n",size); write(s,buffer,strlen(buffer)+1); } } void process_conn_client(int s){ ssize_t size = 0; char buffer[1024]; for(;;){ size = read(0,buffer, 1024); if(size>0){ write(s,buffer,size); size = read(s,buffer,1024); write(1,buffer,size); } } }
4.写一个Makefile编译这三个文件
all:client server client:tcp_proccess.o tcp_client.o gcc -o client tcp_proccess.o tcp_client.o server:tcp_proccess.o tcp_server.o gcc -o server tcp_proccess.o tcp_server.o tcp_proccess.o:tcp_proccess.c gcc -c -o tcp_proccess.o tcp_proccess.c tcp_client.o:tcp_client.c gcc -c -o tcp_client.o tcp_client.c tcp_server.o:tcp_server.c gcc -c -o tcp_server.o tcp_server.c clean: rm -f client server *.o
5.输入make运行Makefile生成可执行文件。
6.先运行服务端./server
7.运行客户端./client 127.0.0.1 ,然后就可以在客户端输入内容了。
hello 6 bytes altogether nihao 6 bytes altogether