客户端/服务器聊天室:处理意外断开连接(Client/server chatroom: Handle unexpected disconnect)

系统教程 行业动态 更新时间:2024-06-14 16:53:07
客户端/服务器聊天室:处理意外断开连接(Client/server chatroom: Handle unexpected disconnect)

我在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);

更多推荐

本文发布于:2023-04-05 21:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/62528d0a05cbfb2bc11faf0a7fdcdbc9.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   聊天室   意外   服务器   Client

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!