Linux下基於socket多線程並發通信的實現
分類: Linux2011-05-21 18:13 8455人閱讀 評論(5) 收藏 舉報socket多線程linuxserverstruct服務器[cpp] view plaincopy
- /***************************************************
- * 文件名:pthread_server.c
- * 文件描述:創建子線程來接收客戶端的數據
- ***************************************************/
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <stdio.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <pthread.h>
- void *rec_data(void *fd);
- int main(int argc,char *argv[])
- {
- int server_sockfd;
- int *client_sockfd;
- int server_len, client_len;
- struct sockaddr_in server_address;
- struct sockaddr_in client_address;
- struct sockaddr_in tempaddr;
- int i,byte;
- char char_recv,char_send;
- socklen_t templen;
- server_sockfd = socket(AF_INET, SOCK_STREAM, 0);//創建套接字
-
- server_address.sin_family = AF_INET;
- server_address.sin_addr.s_addr = htonl(INADDR_ANY);
- server_address.sin_port = htons(9734);
- server_len = sizeof(server_address);
-
- bind(server_sockfd, (struct sockaddr *)&server_address, server_len);//綁定套接字
- templen = sizeof(struct sockaddr);
-
- printf("server waiting for connect/n");
- while(1){
- pthread_t thread;//創建不同的子線程以區別不同的客戶端
- client_sockfd = (int *)malloc(sizeof(int));
- client_len = sizeof(client_address);
- *client_sockfd = accept(server_sockfd,(struct sockaddr *)&client_address, (socklen_t *)&client_len);
- if(-1==*client_sockfd){
- perror("accept");
- continue;
- }
- if(pthread_create(&thread, NULL, rec_data, client_sockfd)!=0)//創建子線程
- {
- perror("pthread_create");
- break;
- }
- }
- shutdown(*client_sockfd,2);
- shutdown(server_sockfd,2);
- }
- /*****************************************
- * 函數名稱:rec_data
- * 功能描述:接受客戶端的數據
- * 參數列表:fd——連接套接字
- * 返回結果:void
- *****************************************/
- void *rec_data(void *fd)
- {
- int client_sockfd;
- int i,byte;
- char char_recv[100];//存放數據
- client_sockfd=*((int*)fd);
- for(;;)
- {
- if((byte=recv(client_sockfd,char_recv,100,0))==-1)
- {
- perror("recv");
- exit(EXIT_FAILURE);
- }
- if(strcmp(char_recv, "exit")==0)//接受到exit時,跳出循環
- break;
- printf("receive from client is %s/n",char_recv);//打印收到的數據
- }
- &