Linux下一个单进程并发服务器的实例 使用select(2)

for (i = 0; i <= maxi; i++) {    
if ( (sockfd = client[i].fd) < 0)       //如果客户端描述符小于0,则没有客户端连接,检测下一个
continue;

if (FD_ISSET(sockfd, &rset)) {        //检测此客户端socket是否有数据   
printf("recv occured for connect fd[%d].\n",i);
if ( (n = recv(sockfd, recvbuf, MAXDATASIZE,0)) == 0) { //从客户端socket读数据,等于0表示网络中断
close(sockfd);        //关闭socket连接
printf("Client( %s ) closed connection. User's data: %s\n",client[i].name,client[i].data);
FD_CLR(sockfd, &allset);    //从监听集合中删除此socket连接
client[i].fd = -1;        //数组元素设初始值,表示没客户端连接
delete client[i].name;
delete client[i].data;
} else
process_cli(&client[i], recvbuf, n);    //接收到客户数据,开始处理
if (--nready <= 0)    
break;       //如果没有新客户端有数据,跳出for循环回到while循环
}
}
}
close(listenfd);  //关闭服务器监听socket    
}

void process_cli(CLIENT *client, char* recvbuf, int len)
{
char sendbuf[MAXDATASIZE];

recvbuf[len-1] = '\0';
if (strlen(client->name) == 0) {
memcpy(client->name,recvbuf, len);
printf("Client's name is %s.\n",client->name);
return;
}

printf("Received client( %s ) message: %s\n",client->name, recvbuf);
savedata(recvbuf,len, client->data);
for (int i1 = 0; i1 < len - 1; i1++) {
sendbuf[i1] = recvbuf[len - i1 -2];
}
sendbuf[len - 1] = '\0';

send(client->fd,sendbuf,strlen(sendbuf),0);
}

void savedata(char* recvbuf, int len, char* data)
{
int start = strlen(data);
for (int i = 0; i < len; i++) {
data[start + i] = recvbuf[i];
}       
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwszgj.html