1. 思路
(1)主线程使用套接字lfd监听连接请求,有新连接请求则提取新连接的套接字cfd,并创建子线程处理该新请求;
(2)主线程继续使用套接字lfd监听并循环提取新连接请求;
(3)子进程中处理新连接套接字cfd的请求即可。
(4)注意:创建子线程之前需要将线程属性设置为分离状态,让内核回收子线程资源,使得父进程可以继续提取新连接。
2.代码实现
#include<stdio.h>
#include<pthread.h>
#include"wrap.h"
typedef struct cli_info {
int cfd;
struct sockaddr_in cliaddr;
}CINFO;
void* client_func(void* arg);
int main(int argc, const char* argv[]) {
// 设置线程分离属性
pthread_attr_t pthattr;
pthread_attr_init(&pthattr);
pthread_attr_setdetachstate(&pthattr, PTHREAD_CREATE_DETACHED);
// 1.创建socket,绑定
int lfd = tcp4bind(8888, NULL);
// 2.监听
Listen(lfd, 128);
// 3.循环提取
struct sockaddr_in cliaddr;
socklen_t len = sizeof(cliaddr);
CINFO* info = NULL;
while (1) {
int cfd = Accept(lfd, (struct sockaddr*)&cliaddr, &len);
char ip[16] = "";
pthread_t tid;
info = malloc(sizeof(CINFO)); // 必须手动在堆区开辟空间,用栈的话下次提取的可能将本次的cfd和cliaddr覆盖。
info->cfd = cfd;
info->cliaddr = cliaddr;
pthread_create(&tid, &pthattr, client_func, info);
}
pthread_attr_destroy(&pthattr);
return 0;
}
void* client_func(void* arg) {
CINFO* info = (CINFO*)arg;
char ip[16] = "";
printf("新客户端%d到来!ip = %s, port = %d\n", info->cfd,
inet_ntop(AF_INET, &(info->cliaddr.sin_addr.s_addr), ip, 16),
ntohs(info->cliaddr.sin_port));
while (1) {
char buf[1024] = "";
int n = read(info->cfd, buf, sizeof(buf));
if (n < 0) {
perror("read");
break;
} else if (0 == n) {
printf("客户端关闭.\n");
break;
} else {
printf("客户端:%s\n", buf);
write(info->cfd, buf, n);
}
}
close(info->cfd);
free(info);
return NULL;
}
运行结果: