当连接开关切换数据时,如果没有要传输的数据,会发生什么情况?

huangapple go评论65阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年4月19日 22:26:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/71927067.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定