|
EDA365欢迎您登录!
您需要 登录 才可以下载或查看,没有帐号?注册
x
本帖最后由 ulppknot 于 2019-9-26 13:34 编辑
# }% ~: S5 z4 z' ^4 `9 o9 ]/ g: m) R6 y, f0 W* |4 i1 O3 P8 L! X5 \& H
2 ^6 F) l" S; H9 W
- /***************************************************
- * 文件名:pthread_server.c
- * 文件描述:创建子线程来接收客户端的数据
- * louis tested
- ***************************************************/
- #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>
- #include <time.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;
- int res;
- server_sockfd = socket(AF_INET, SOCK_STREAM, 0);//创建套接字
- server_address.sin_family = AF_INET;
- server_address.sin_addr.s_addr = inet_addr("192.168.1.40"); //htonl(INADDR_ANY);
- server_address.sin_port = htons(8888);
- server_len = sizeof(server_address);
- res= bind(server_sockfd, (struct sockaddr *)&server_address, server_len);//绑定套接字
- if(res == -1)
- {
- perror("bind failed");
- exit(-1);
- }
- templen = sizeof(struct sockaddr);
- res= listen(server_sockfd, 100);// louis 原来的代码确实listen 调试不过
- if(res == -1)
- {
- perror("listen failed");
- exit(-1);
- }
- 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;
- }else{
- printf("pthread_created\n");
- }
- sleep(1);
- }
- 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);//打印收到的数据
- }
- free(fd);
- close(client_sockfd);
- pthread_exit(NULL);
- }
- 2 m' G0 L m) d
& O/ z5 |9 F6 J5 l" o5 H
+ X' K3 S: k# L' y1 g
' |7 y! |& J. U
7 ^" t U" E# l$ ~1 \# I* _: h9 V9 U
6 s. r3 x% S8 C. [
pthread_client.c
9 ~7 c. _6 s5 X# M/ w/ @8 \2 X! [0 K( N+ l) S) Z/ L
4 Y2 a2 D, e# h |
|