#! https://zhuanlan.zhihu.com/p/538247988
socket通信-多线程
使用多线程完成,对每个线程传递对应的位次号,虽然每个线程都调用同一个函数,但是函数中接收函数的文件描述符不同,通过设置数组实现。
static void *new_thread_start(void *arg)
{
int ret, thread_count=0;
char ip_str[20] = {0};
char recvbuf[512];
thread_count = *((int *)arg);
//pthread_mutex_lock(&mutex);
printf("There is client access..\n");
printf("This threadID=%lu \n", pthread_self());
printf("There is client%d access..\n", thread_count);
inet_ntop(AF_INET, &client_addr.sin_addr, ip_str, sizeof(ip_str));
printf("The IP address of the client host is: %s\n", ip_str);
printf("The port number of the client process is: %d\n", client_addr.sin_port);
for ( ; ; )
{
/* code */
memset(recvbuf, 0x0, sizeof(recvbuf));
ret = recv(connfd[thread_count], recvbuf, sizeof(recvbuf), 0);
if(0 >= ret)
{
perror("recv error");
close(connfd[thread_count]);
break;
}
printf("from client%d:%s\n", thread_count ,recvbuf);
if(0 == strncmp("exit", recvbuf, 4))
{
printf("server exit...\n");
close(connfd[thread_count]);
break;
}
}
close(sockfd);
pthread_exit(NULL);
exit(EXIT_SUCCESS);
//pthread_mutex_unlock(&mutex);
}