1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <time.h> 5 #include <sys/types.h> /* See NOTES */ 6 #include <sys/socket.h> 7 #include <netinet/in.h> 8 #include <netinet/ip.h> 9 #include <arpa/inet.h> 10 #include <unistd.h> 11 #include <sys/wait.h> 12 #include <pthread.h> 13 14 int Server_init(void); 15 typedef struct sockaddr SA; 16 17 void *callback(void* confd); 18 int main(int argc,const char *argv[]) 19 { 20 int sockfd; 21 //初始化套接字 22 sockfd=Server_init(); 23 24 return 0; 25 } 26 27 int Server_init(void) 28 { 29 //创建套接字 30 int sockfd=socket(AF_INET,SOCK_STREAM,0); 31 if(sockfd==-1) 32 { 33 perror("sockfd"); 34 return -1; 35 } 36 37 //绑定套接字 38 struct sockaddr_in seraddr; 39 seraddr.sin_family=AF_INET; 40 seraddr.sin_port=htons(8080); 41 seraddr.sin_addr.s_addr=htonl(INADDR_ANY); 42 int ret=bind(sockfd,(SA*)&seraddr,sizeof(seraddr)); 43 if(ret==-1) 44 { 45 perror("bind"); 46 return -1; 47 } 48 49 //监听 50 ret=listen(sockfd,0); 51 if(ret==-1) 52 { 53 perror("listen"); 54 return -1; 55 } 56 printf("listen--successful\n"); 57 //接通 58 struct sockaddr_in cliaddr; 59 socklen_t len=sizeof(cliaddr); 60 while(1) 61 { 62 int confd=accept(sockfd,(SA*)&cliaddr,&len); 63 if(confd==-1) 64 { 65 perror("accept"); 66 return -1; 67 } 68 printf("accept--successful %s %d\n",inet_ntoa(cliaddr.sin_addr),ntohs(cliaddr.sin_port)); 69 pthread_t thread_id; 70 int ret=pthread_create(&thread_id,NULL,callback,(void*)confd); //把连接套接字直接发过去 71 if(ret==-1) 72 { 73 perror("pthread_create"); 74 return -1; 75 } 76 pthread_detach(thread_id); 77 } 78 close(sockfd); 79 } 80 81 void *callback(void* confd) 82 { 83 int id=(int)confd; //注意:关闭套接字时,需要一个局部变量 84 while(1) 85 { 86 char buf[64]; 87 bzero(buf,sizeof(buf)); 88 strcpy(buf,"hello ,this is server"); 89 //发送数据 90 send(id,buf,sizeof(buf),0); 91 } 92 close(id); 93 pthread_exit(NULL); 94 }