1 多线程并发服务器思路分析
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210411013909360.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0xfaW5zdGluZw==,size_16,color_FFFFFF,t_70)
2 多线程并发服务器代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#include <pthread.h>
void *Func(void *argv)
{
int cfd = *(int*)argv;
int n = 0;
char buf[1024] = {0};
while (1)
{
memset(buf, 0, sizeof(buf));
n = read(cfd, buf, sizeof(buf));
if (-1 == n)
{
if (errno == EINTR)
{
continue;
}
else
{
perror("read error\n");
close(cfd);
return (void*)-1;
}
}
else if (0 == n)
{
printf("断开连接\n");
close(cfd);
return 0;
}
else
{
printf("%s\n", buf);
}
}
pthread_exit(NULL);
}
int main()
{
int ret = 0;
int sfd = 0;
int cfd[128] = {0};
int i = 0;
pthread_t threadID;
sfd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == sfd)
{
perror("socket error");
exit(1);
}
struct sockaddr_in saddr, caddr;
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8000);
saddr.sin_addr.s_addr = inet_addr("192.168.71.132");
ret = bind(sfd, (struct sockaddr*)&saddr, sizeof(saddr));
if (-1 == ret)
{
perror("bind error");
close(sfd);
exit(1);
}
ret = listen(sfd, 5);
if (-1 == ret)
{
perror("listen error");
close(sfd);
exit(1);
}
while (1)
{
socklen_t caddrLen = sizeof(caddr);
cfd[i] = accept(sfd, (struct sockaddr*)&caddr, &caddrLen);
if (-1 == cfd[i])
{
if (errno == EINTR)
{
continue;
}
perror("accept error");
exit(1);
}
else
{
printf("连接成功[%s:%d]\n", inet_ntoa(caddr.sin_addr), ntohs(caddr.sin_port));
ret = pthread_create(&threadID, NULL, Func, (void*)(&cfd[i]));
if (ret != 0)
{
printf("pthread_create error:%s\n", strerror(ret));
exit(1);
}
ret = pthread_detach(threadID);
if (ret != 0)
{
printf("pthread_detach error:%s\n", strerror(ret));
exit(1);
}
i++;
continue;
}
}
return 0;
}