我在C写了一个服务器 - 客户端聊天室。
服务器为每个到客户端的新连接创建一个新的pthread,这个pthread等待接收消息,并将此消息发送给所有其他客户端(使用所有文件描述符的数组)。 如果客户端想要退出,他会通知服务器,他将终止pthread并从数组中删除文件描述符
这很好用!但是:
如果客户端断开意外,通过关闭终端,例如,服务器将不会从数组中删除文件描述符,当其他客户端想要发送消息时,我有一个错误,因为pthread尝试将消息发送到fd这不再是一种联系
现在我的问题:
在发送消息之前,如何测试客户端套接字的文件描述符是否仍然有效?
我的代码部分(来自pthread):
for(i=0; i<*p_Nbr_Clients; i++){ // send the message to all the other clients if (fd_array[i] != fd){ // <- i want to test the fd here if ( send(fd_array[i], msg, strlen(msg), 0) == -1 ){ perror("Serveur: send"); } } }I wrote in C a server - client chatroom.
The server creates a new pthread for every new connection to a client, this pthread waits for a message to receive, and sends this message to all the other clients (using a array of all the file descriptors). If a client wants to quit he informs the server and he will terminate the pthread and delete the file descriptor from the array
This works fine !, but:
if a client disconnects unexpected, by closing the terminal for example, the server won't delete the file descriptor from the array and when an other client wants to send a message i have an error because the pthread tries to send the message to a fd which isn't a connection any more
Now my question:
How can in test if the file descriptor of a client's socket is still active before i send a message ?
the part of my code (from the pthread):
for(i=0; i<*p_Nbr_Clients; i++){ // send the message to all the other clients if (fd_array[i] != fd){ // <- i want to test the fd here if ( send(fd_array[i], msg, strlen(msg), 0) == -1 ){ perror("Serveur: send"); } } }最满意答案
检查recv()的返回值。
如果用户异常终止,则返回值应为零0。
基于此,您可以轻松关闭fd。
if(recv(fd,buffer,length,flag) == 0) close(fd);Check the return value of the recv().
If the user terminated abnormally then return value should be zero 0.
Based on that you can close fd easily.
if(recv(fd,buffer,length,flag) == 0) close(fd);更多推荐
发布评论