多线程并发服务器的简单实现

分析同多进程并发

代码实现

  1 //多线程服务器
  2 #include"wrap.h"
  3 #include<sys/types.h>
  4 #include<sys/wait.h>
  5 #include<pthread.h>
  6 #define SERV_PORT 8888
  7 //客户端的信息封装在一起,传给线程去处理
  8 struct c_info
  9 {
 10     int cfd;
 11     struct sockaddr_in caddr;
 12 };
 13 
 14 void *pthread_func(void *arg)
 15 {
 16     int n;
 17     char buf[BUFSIZ];
 18     char str[128];
 19     struct c_info *info = (struct c_info *)arg;
 20 
 21     printf("Client ip =%s ,port =%d\n ",inet_ntop(AF_INET,&(info->caddr.sin_addr.s_addr),str,sizeof(str))
 22                 ,ntohs(info->caddr.sin_port));
 23 
 24     while(1)
 25     {
 26         n=Read(info->cfd,buf,sizeof(buf));
 27         if(n==0)
 28         {
 29             printf("client %d is closing\n",info->cfd);
 30              break;
 31         }
 32         else if(n == -1)
 33         {
 34             perror("Read error");
 35             pthread_exit(NULL);
 36         }
 37         else
 38         {
 39             int i=0;
 40             for(i=0;i<n;i++)
 41               buf[i]=toupper(buf[i]);
 42             write(info->cfd,buf,n);
 43         }
 44 
 45     }
 46 }
 47 int main()
 48 {
 49     int lfd,cfd;
 50     pthread_t tid;
 51     struct c_info info[128];//最大可接受128客户端,即最大128个线程
 52     struct sockaddr_in saddr,caddr;
 53     lfd = Socket(AF_INET,SOCK_STREAM,0);
 54 
 55     bzero(&saddr,sizeof(saddr));
 56     bzero(&caddr,sizeof(caddr));
 57     saddr.sin_family = AF_INET;
 58     saddr.sin_port = htons(SERV_PORT);
 59     inet_pton(AF_INET,"127.0.0.1",&saddr.sin_addr.s_addr);
 60     Bind(lfd,(struct sockaddr*)&saddr,sizeof(saddr));
 61 
 62     Listen(lfd,128);
 63     int i=0;
 64     printf("Accepting client connect .....\n");
 65     while(1)
 66     {
 67         socklen_t len = sizeof(caddr);
 68         cfd = Accept(lfd,(struct sockaddr*)&caddr ,&len);//阻塞监听客户端
 69         info[i].cfd =cfd;
 70         info[i].caddr=caddr;
 71 
 72         pthread_create(&tid,NULL,pthread_func,(void *)&info[i]);
 73         pthread_detach(tid); //线程分离,防止无法回收形成僵尸线程
 74         i++;
 75     }
 76 
 77     return 0;
 78 }

执行结果

yan@ubuntu:~/net/3$ ./Server
Accepting client connect …
Client ip=127.0.0.1 ,port =60666
Client ip =127.0.0.1 ,port =60668
Client ip =127.0.0.1 ,port =60672
client 4 is closing
client 5 is closing
client 6 is closing

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YanWenCheng_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值