0
// 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
  • 1
    There is the issue of OS write buffer, and TCP no-delay (the default is to not delay packets, but you might have set it otherwise), and other factors that can cause a write not to actually send packets to the other side. Mar 3, 2015 at 11:41

1 Answer 1

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.