Linux下TCP/IP网络编程示例——实现服务器/客户端通信(三):基于socket实现基本的服务器与客户端通信,使用多线程实现服务端的多并发功能。
例程中使用多线程来实现多并发,每新来一个客户端连接请求,就新开一个线程去与该客户端进行通信。当对应客户端退出时,服务器结束对应的线程,为了及时回收结束线程的资源,在每次创建线程前,都先设置线程的分离属性,使得线程结束后,由系统自动回收线程资源。
server.c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <fcntl.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERVER_PORT 6000
#define SERVER_IP "192.168.99.112"
int listen_fd = -1;
static int set_pthread_detach_attr(pthread_attr_t *attr);
static void * client_msg_proc(void *arg);
/*
** 按Ctrl+C退出server程序时,执行下面操作关闭监听套接字
*/
void signal_handler(int arg)
{
printf("close listen_fd(signal = %d)\n", arg);
close(listen_fd);
exit(0);
}
int main(int argc, const char *argv[])
{
int new_fd = -1;
struct sockaddr_in server;
struct sockaddr_in client;
socklen_t saddrlen = sizeof(server);
socklen_t caddrlen = sizeof(client);
signal(SIGINT, signal_handler);
memset(&server, 0, sizeof(server));
memset(&client, 0, sizeof(client));
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if (listen_fd < 0)
{
printf("socket error!\n");
return -1;
}
server.sin_family = AF_INET;
server.sin_port = htons(SERVER_PORT);
server.sin_addr.s_addr = inet_addr(SERVER_IP);
if (bind(listen_fd, (struct sockaddr *)&server, saddrlen) < 0)
{
printf("bind error!\n");
return -1;
}
if (listen(listen_fd, 5) < 0)
{
printf("listen error!\n");
return -1;
}
while (1)
{
new_fd = accept(listen_fd, (struct sockaddr *)&client, &caddrlen);
if (new_fd < 0)
{
perror("accept error");
return -1;
}
printf("new client connected(%d).IP:%s,port:%u\n", new_fd, inet_ntoa(client.sin_addr), ntohs(client.sin_port));
int ret = 0;
pthread_t tid = 0;
pthread_attr_t thread_attr;
ret = set_pthread_detach_attr(&thread_attr);
if (ret == -1)
{
printf("error:set_pthread_detach_attr failed!\n");
return -1;
}
if (pthread_create(&tid, &thread_attr, client_msg_proc, (void *)&new_fd) != 0)
{
perror("pthread_create");
return -1;
}
//printf("tid=%ld\n", tid);
ret = pthread_attr_destroy(&thread_attr);
if (ret != 0)
{
printf("error:pthread_attr_destroy failed!\n");
return -1;
}
}
close(listen_fd);
return 0;
}
/*
** 线程回调函数,处理接收客户端的消息
*/
static void * client_msg_proc(void *arg)
{
int linkfd = *(int *)arg;
size_t rsize = 0;
char rbuf[200] = {0};
while (1)
{
rsize = read(linkfd, rbuf, sizeof(rbuf));
if (rsize < 0)
{
printf("read error!\n");
continue;
}
else if (rsize == 0)
{
printf("client (fd = %d) is closed!\n", linkfd);
close(linkfd);
pthread_exit(NULL);
}
printf("recv from link=%d:%s\n", linkfd, rbuf);
}
}
/*
** 设置线程的分离属性
** 设置该属性后,线程结束后,由系统自动回收线程资源
*/
static int set_pthread_detach_attr(pthread_attr_t *attr)
{
int ret = 0;
ret = pthread_attr_init(attr);
if (ret != 0)
{
printf("error:pthread_attr_init failed!\n");
return -1;
}
ret = pthread_attr_setdetachstate(attr, PTHREAD_CREATE_DETACHED);
if (ret != 0)
{
printf("error:pthread_attr_setdetachstate failed!\n");
return -1;
}
return 0;
}