// 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?
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
orconnection 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.