英文:
When conn switch data, if there is no data for transmitting, what will happen?
问题
当我阅读这段开源代码时,我看到下面的代码:
streamConn := func(dst io.Writer, src io.Reader) {
io.Copy(dst, src)
streamWait.Done()
}
go streamConn(remoteConn, conn)
go streamConn(conn, remoteConn)
你可以看到使用了两个go streamConn()
来在两个conn
之间传输数据。
我想知道如果remoteConn
没有要传输的数据,会复制什么?是复制nil
吗?
英文:
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
?
答案1
得分: 1
通常,网络套接字以阻塞模式运行-如果没有更多要接收的数据,那么“接收”操作将会一直等待,直到有数据为止。这就是为什么有两个goroutine,一个在每个方向上-这样一个可以在另一个仍在等待数据(在读取时被阻塞)的时候继续复制数据。
在同一文件的稍上方,你会找到一个对remoteConn.Read(data)
的直接调用的类似示例。当调用时,Read()不会返回,直到它获得一些数据-或者直到它达到使用SetReadDeadline()设置的超时(在这种情况下,它将通过err
返回一个超时错误)。
英文:
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
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论