开发者

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?


A TcpClient object wraps a NetworkStream object. 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. The MSDN article for NetworkStream says the following:

Read and write operations can be performed simultaneously on an instance of the NetworkStream class without the need for synchronization. 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. Use the TcpClient object returned from the call to AcceptTcpClient() to communicate (read and write) with the remote endpoint.


TCP connection is a full-duplex pipe, take a look here. You don't need a separate port or anything else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜