C 套接字:在套接字关闭时避免垃圾

发布于 2024-11-05 14:32:30 字数 261 浏览 9 评论 0原文

我正在使用非阻塞套接字(fd_setsselect 函数)对服务器和客户端进行编程,一旦服务器关闭或关闭客户端套接字,客户端就会开始接收很多垃圾直到崩溃.. 有人警告我,在使用 select() 时,连接终止时套接字将变得可读,但我如何知道

if( FD_ISSET( socket, &read ) ) 
{
} 

原因是只是常规数据还是连接已结束?

I'm programming a server and a client using non blocking sockets (fd_sets and select function) and once the server closes or shuts down a client socket, the client starts receiving a lot of garbage until it crashes..
I've been warned that when working with select() a socket would become readable when the connection was terminated, but how can I know in

if( FD_ISSET( socket, &read ) ) 
{
} 

if the cause is just regular data or the connection has ended?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

樱娆 2024-11-12 14:32:30

文件描述符集不会告诉您套接字是否已关闭,只会告诉您可以尝试从中读取数据。当远程端关闭连接时,套接字将变为“可读”。当您尝试 recv() 时,返回值将为 0,表示连接已关闭。始终检查您的返回值。

The file descriptor sets wont tell you if the socket is closed, only that you may attempt to read from it. When the remote end closes the connection the socket will become "readable". When you attempt a recv() the return value will be 0 indicating the connection is closed. Always check your return values.

那些过往 2024-11-12 14:32:30

您将不得不使用 poll (它也更灵活,因为它不受 FD_SET 大小的限制!)

struct poll p = {.fd = fd, .events = POLLHUP|POLLRDHUP};

You will have to use poll instead (it's also more flexible because it's not bound by the size of FD_SET!)

struct poll p = {.fd = fd, .events = POLLHUP|POLLRDHUP};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文