dongxixiu9134 2015-03-03 11:21
浏览 127

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
}

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.

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

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?

  • 写回答

1条回答 默认 最新

  • dongli564510 2015-03-03 15:15
    关注

    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).

    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.

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?