在不发送或接收的情况下检测套接字挂断? [英] Detect socket hangup without sending or receiving?

查看:35
本文介绍了在不发送或接收的情况下检测套接字挂断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 TCP 服务器,它可能需要 15 秒或更长时间才能开始生成对某些请求的响应正文.如果响应需要超过几秒钟才能完成,一些客户端喜欢在他们结束时关闭连接.

I'm writing a TCP server that can take 15 seconds or more to begin generating the body of a response to certain requests. Some clients like to close the connection at their end if the response takes more than a few seconds to complete.

由于生成响应会占用大量 CPU,因此我更愿意在客户端关闭连接时立即停止任务.目前,直到我发送第一个payload并收到各种挂断错误,我才发现这一点.

Since generating the response is very CPU-intensive, I'd prefer to halt the task the instant the client closes the connection. At present, I don't find this out until I send the first payload and receive various hang-up errors.

如何在不发送或接收任何数据的情况下检测到对等方已关闭连接?这意味着对于 recv 来说所有数据都保留在内核中,或者对于 send 来说实际上没有数据被传输.

How can I detect that the peer has closed the connection without sending or receiving any data? That means for recv that all data remains in the kernel, or for send that no data is actually transmitted.

推荐答案

我在与具有单独的 TCP 链接进行发送和接收的设备进行通信时经常遇到问题.基本问题是,TCP 堆栈通常不会在您尝试读取时告诉您套接字已关闭-您必须尝试写入才能被告知链接的另一端已删除.在某种程度上,这就是 TCP 的设计方式(读取是被动的).

I've had a recurring problem communicating with equipment that had separate TCP links for send and receive. The basic problem is that the TCP stack doesn't generally tell you a socket is closed when you're just trying to read - you have to try and write to get told the other end of the link was dropped. Partly, that is just how TCP was designed (reading is passive).

我猜布莱尔的回答适用于套接字在另一端很好地关闭的情况(即他们发送了正确的断开连接消息),但不适用于另一端不礼貌地停止监听的情况.

I'm guessing Blair's answer works in the cases where the socket has been shut down nicely at the other end (i.e. they have sent the proper disconnection messages), but not in the case where the other end has impolitely just stopped listening.

在您的消息的开头是否有一个相当固定格式的标头,您可以在整个响应准备好之前通过发送开始?例如XML 文档类型?此外,您是否能够避免在消息的某些点发送一些额外的空格——只是一些您可以输出的空数据以确保套接字仍然打开?

Is there a fairly fixed-format header at the start of your message, that you can begin by sending, before the whole response is ready? e.g. an XML doctype? Also are you able to get away with sending some extra spaces at some points in the message - just some null data that you can output to be sure the socket is still open?

这篇关于在不发送或接收的情况下检测套接字挂断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆