When I read the opensource code:
there have this code below:
streamConn := func(dst io.Writer, src io.Reader) {
io.Copy(dst, src)
streamWait.Done()
}
go streamConn(remoteConn, conn)
go streamConn(conn, remoteConn)
you see there use two go streamConn()
to switch the data between two conn
.
and I want to know if the remoteConn
do not have data to transmit, there copy what? copy nil
?
CodePudding user response:
Usually network sockets operate in blocking mode – if there's no more data to be received, then the "receive" operation will just sit there and wait until there is some. That's why there are two goroutines, one in each direction – so that one could keep copying data while the other is still waiting for data (blocked on read).
For a similar but more direct example, you'll find a direct call to remoteConn.Read(data)
a bit higher up in the same file. When called, Read() won't return until it gets some data – or until it reaches the timeout that was set using SetReadDeadline() immediately above (in which case it'll return a Timeout error through err
).