1 实现思路
- 在主线程中循环accept()函数阻塞等待客户端连接请求,每接收一个连接请求就创建一个子线程;
- 在子线程的回调函数中实现客户端与服务端的通信;
- 设置线程分离,子线程终止时自动释放资源。
注意事项:
- 由于pthread_create()创建子线程时,需要向回调函数传递的参数有文件描述符和专用Socket地址,因此需将这些参数放到一个结构体中,然后把结构体的地址作为参数传入。
- 创建结构体数组来存放每一次连接的信息,避免线程之间共享套接字的问题,具体可参考博客:
https://blog.csdn.net/qq_28114615/article/details/88536156
2 服务端程序
#include <iostream>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define SERV_PORT 9998
#define MAX_CON 128
using namespace std;
struct sockInfo{
int fd; //文件描述符
struct sockaddr_in addr;
};
void * conn(void * arg) {
sockInfo * pinfo = (struct sockInfo*) arg;
//输出连接客户端信息
char ClientIP[16];
inet_ntop(AF_INET, &pinfo->addr.sin_addr.s_addr, ClientIP, 16);
cout << "client ip: " << ClientIP << ", port: " << ntohs(pinfo->addr.sin_port) << endl;
while(1) {
char recvBuf[1024];
int len = 0;
if((len = read(pinfo->fd, recvBuf, sizeof(recvBuf))) > 0) {
cout << "(SERVER) recv data: " << recvBuf << " (from port: " << ntohs(pinfo->addr.sin_port) << ")"<< endl;
int i = 0;
for(i = 0; i < len; i++) {
recvBuf[i] = toupper(recvBuf[i]);
}
recvBuf[i] = '\0';
write(pinfo->fd, recvBuf, strlen(recvBuf)); //转为大写后发回
}
else if(len == 0) {
cout << "(SERVER) client, from port: " << ntohs(pinfo->addr.sin_port) << " closed..." << endl;
break;
}
else if(len == -1) {
perror("read");
exit(-1);
}
}
close(pinfo->fd);
return 0; //退出子线程
}
int main() {
sockInfo lskt, cskt;
pthread_t tid;
sockInfo sockInfos[MAX_CON];
memset(&lskt, 0, sizeof(lskt));
memset(&cskt, 0, sizeof(cskt));
//创建服务端套接字
if((lskt.fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(-1);
}
//为服务端地址结构赋值
lskt.addr.sin_family = AF_INET;
lskt.addr.sin_port = htons(SERV_PORT);
lskt.addr.sin_addr.s_addr = htonl(INADDR_ANY);
//设置端口复用
socklen_t optval = 1;
setsockopt(lskt.fd, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
//绑定服务端地址信息
if(bind(lskt.fd, (sockaddr *)&lskt.addr, sizeof(lskt.addr)) == -1) {
perror("bind");
exit(-1);
}
//监听socket上的连接
if(listen(lskt.fd, 128) == -1) {
perror("listen");
exit(-1);
}
char ServerIP[16];
inet_ntop(AF_INET, &lskt.addr.sin_addr.s_addr, ServerIP, 16);
cout << "init success" << endl;
cout << "host ip: " << ServerIP << ", port: " << ntohs(lskt.addr.sin_port) << endl;
//初始化sockInfos结构体数组
for(int i = 0; i < MAX_CON; i++) {
bzero(&sockInfos[i], sizeof(sockInfos[i]));
sockInfos[i].fd = -1;
}
//不断循环等待客户端连接
while(1) {
socklen_t len = sizeof(cskt.addr);
if((cskt.fd = accept(lskt.fd, (sockaddr *)&cskt.addr, &len)) == -1) {
perror("accept");
exit(-1);
}
sockInfo * pinfo;
for(int i = 0; i < MAX_CON; i++) {
if(sockInfos[i].fd == -1) {
pinfo = &sockInfos[i];
break;
}
if(i == MAX_CON - 1){
sleep(1);
i--;
}
}
memcpy(pinfo, &cskt, sizeof(cskt));
//创建子线程
pthread_create(&tid, NULL, conn, (void *)pinfo);
//设置线程分离,线程终止时自动释放资源
pthread_detach(tid);
}
close(lskt.fd);
return 0;
}