#include <arpa/inet.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <pthread.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> void* socketProcess(void* socket_desc ); int main(int argc, char const* argv[]) { int sock_desc,c,recv_len; int *new_sock; char client_message[512]; struct sockaddr_in server,client; sock_desc=socket(AF_INET,SOCK_STREAM,0); if(sock_desc<0){ puts("错误"); return 1; } server.sin_addr.s_addr=INADDR_ANY; server.sin_port=htons(8888); server.sin_family=AF_INET; if(bind(sock_desc,(struct sockaddr*)&server,sizeof(server))<0){ puts("绑定错误"); } puts("绑定完成"); listen(sock_desc,5); puts("正在监听等待连接"); while(1){ new_sock=(int*)malloc(sizeof(int)); *new_sock=accept(sock_desc,(struct sockaddr*)&client,(socklen_t* )&c); pthread_t thread_id; puts("接受请求"); if(*new_sock!=-1){ char ipv4addr[100]; char addr_buf[INET_ADDRSTRLEN]; socklen_t len; if(getsockname(*new_sock,(struct sockaddr*)&client,&len)==-1) { perror("gesockname err"); } printf("ip:%d\n",ntohs(client.sin_port)); if(pthread_create(&thread_id,0,&socketProcess,(void*)new_sock)<0){//创建一个线程 perror("创建线程失败"); return 1; } pthread_detach(thread_id);//线程分离 } puts("新客户连接"); } puts("连接成功"); return 0; } void* socketProcess(void* socket_desc ){ int *csock = (int*)socket_desc; char buffer[1024]; int buffer_len = 1024; int bytecount; while(1){ memset(buffer, 0, buffer_len); if((bytecount = recv(*csock, buffer, buffer_len, 0))== -1){ fprintf(stderr, "接收数据错误,错误代码: %d\n", errno); close(*csock); return(0); } printf("接收到字节数 %d\n接收字符串 \"%s\"\n", bytecount, buffer); strcat(buffer, " SERVER ECHO\n"); if((bytecount = send(*csock, buffer, strlen(buffer), 0))== -1){ fprintf(stderr, "错误发送数据 %d\n", errno); close(*csock); return(0); } printf("发送字节数 %d\n", bytecount); } return 0; }