golang写入net conn而不返回错误,但套接字的另一端无法接收数据 [英] golang write net conn without returning error but the other side of the socket can't receive data

查看:72
本文介绍了golang写入net conn而不返回错误,但套接字的另一端无法接收数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// only Data
func (self *Packet) WriteData(w io.Writer) error {
    n := len(self.Data)
    data := self.Data[0:n]
    for n > 0 {
        wn, err := w.Write(data)
        data = data[wn:n]
        n -= wn
        if err != nil {
            return err
        }
    }
    return nil
}

当我使用net.Conn(由net.Dial("tcp")创建)调用WriteData函数时,它返回nil,但是套接字的其他端口有时无法接收发送的数据.

When I call the WriteData function with a net.Conn (created by net.Dial("tcp")), it returns nil but the other port of the socket can't receive the sent data sometimes.

似乎连接已断开,但是w.Write仍然返回而没有错误.

It seems the connection was broken, but w.Write still returns without error.

在我的脑海中,当此套接字的另一端没有收到数据包时,w.Write不应无错误地返回,所以我错过了什么吗?

In my mind w.Write shouldn't return without error when the other side of this socket doesn't receive the packet, so is there something I missed?

推荐答案

这是TCP协议如何工作的功能.无法确定您是否要事先发送到关闭的套接字(即使有,发送和关闭也会发生争用).

This is a function of how the TCP protocol works. There's is no way to determine if you're sending to a closed socket before hand (even if there were, sending and closing would race).

如果关闭了远程套接字,您最终将收到错误,断开的管道由对等方重置的连接.仅仅因为有berkley套接字API,您通常在第二次发送操作之前看不到它.这依赖于远程主机以RST响应或中介发送ICMP信号,因此,如果数据包被延迟或丢失,则仍然有可能,并且您可以继续发送而不会出现错误.

If a remote socket is closed, you will eventually get an error, broken pipe or connection reset by peer. Simply because of the berkley socket api, you often won't see this until your second send operation. This relies on the remote host responding with an RST, or an intermediary sending an ICMP signal, so it still is possible that if the packets are delayed or lost, and you can continue sending without an error.

可靠地检测到关闭的连接的唯一方法是从连接中读取,并获得0字节的响应,然后将其转换为EOF.

The only way to reliably detect a closed connection is to Read from a connection, and and get a 0 byte response, which go translates to EOF.

这篇关于golang写入net conn而不返回错误,但套接字的另一端无法接收数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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