[英]How to create a duplex connection using TcpListener and TcpClient?
I have a situation where I need to send and receive information parallelly. 我有一种需要并行发送和接收信息的情况。
My protocol can define a read port and a write port. 我的协议可以定义读端口和写端口。
I currently have the following code: 我目前有以下代码:
public void Listen()
{
ThreadPool.SetMinThreads(50, 50);
listener.Start();
while (true)
{
var context = new ListeningContext(listener.AcceptTcpClient(), WritePort);
}
}
How can I create another listener from the TcpClient I am passing? 如何从我传递的TcpClient创建另一个侦听器?
A TcpClient
object wraps a NetworkStream
object. TcpClient
对象包装NetworkStream
对象。 You use the GetStream()
method of TcpClient
to access the NetworkStream
object, which is then used to read data from and write data to the network. 您可以使用
TcpClient
的GetStream()
方法访问NetworkStream
对象,然后使用该对象从网络读取数据并将数据写入网络。 The MSDN article for NetworkStream
says the following: NetworkStream
的MSDN文章说明如下:
Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization.
可以在NetworkStream类的实例上同时执行读写操作,而无需同步。 As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.
只要有一个用于写操作的唯一线程和一个用于读操作的唯一线程,读写线程之间就不会存在交叉干扰,也不需要同步。
Use the TcpListener
object to listen for incoming connections. 使用
TcpListener
对象侦听传入连接。 Use the TcpClient
object returned from the call to AcceptTcpClient()
to communicate (read and write) with the remote endpoint. 使用从
AcceptTcpClient()
调用返回的TcpClient
对象与远程端点进行通信(读取和写入)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.