写上由对等关闭的TCP套接字 [英] Writing on a TCP socket closed by the peer

查看:182
本文介绍了写上由对等关闭的TCP套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有其中每一个侧经由TCP套接字与其他通信的客户端 - 服务器应用

I have a client-server application where each side communicate with the other via TCP socket.

我正常建立连接,然后我崩溃的服务器之前的任何数据由客户端套接字上写的。结果
我看到的是,第一个的write()尝试(客户端)是成功的,它返回写入的字节的实际数量,而下面的人回报(如我所料) 1 (接收 SIGPIPE )和错误号= EPIPE

I properly establish the connection and then I crash the server BEFORE any data is written on the socket by the client.
What I see is that the first write() attempt (client-side) is successful and it returns the actual number of written bytes, while the following ones return (as I expected) -1 (receiving a SIGPIPE) and errno=EPIPE.

为什么第一个的write()成功,即使套接字已经关闭?

Why the first write() is successful even if the socket is already closed?

修改
有时还有以下的write()有正收益值,如果一切顺利的话。

EDIT Sometimes also the following write() have a positive return values, as if everything goes well.

推荐答案

您是通过何种的write()的返回值表示困惑。这并不意味着,对等得到的数据,并确认它。相反,它的意思是我缓冲,所以,多少字节发送给对方,他们现在是我的责任,所以你可以对他们忘了(我没有任何未决错误)。

You're confused by what the return value of write() means. It doesn't mean, "the peer got the data and acknowledged it". Instead, it means, "I buffered so-many bytes to send to the peer and they're my responsibility now, so you can forget about them (and I don't have any pending errors)".

也就是说,如果TCP堆栈接受写入和回报的 N 的字节数,这并不意味着他们已经没有写,只是排队等待写入。它开始发送网络流量后,前栈放弃并返回一个错误给你它会需要一些时间,也许是30秒。在此期间,你可以做多次打电话给的write()这是成功地发送排队的数据。 (写错误将在c.30s如果对方已经消失,或者立即如果对等可联系并发送RST包马上表示连接是死被退回。)

That is, if the TCP stack accepts the write and returns n bytes, that doesn't mean they've been written yet, just queued for writing. It'll take some time, perhaps 30s after it starts sending network traffic, before the stack gives up and returns an error to you. During that time, you could have done several calls to write() which were successful at queueing data for sending. (The write error will be returned in c.30s if the peer has vanished, or immediately if the peer can be contacted and sends a RST packet straight away to indicate the connection is dead.)

这篇关于写上由对等关闭的TCP套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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