如何使用 TcpListener 和 TcpClient 创建双工连接? [英] How to create a duplex connection using TcpListener and TcpClient?

查看:24
本文介绍了如何使用 TcpListener 和 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.

我目前有以下代码:

public void Listen()
{
    ThreadPool.SetMinThreads(50, 50);
    listener.Start();

    while (true)
    {
        var context = new ListeningContext(listener.AcceptTcpClient(), WritePort);
    }
}

如何从我传递的 TcpClient 创建另一个侦听器?

How can I create another listener from the TcpClient I am passing?

推荐答案

一个 TcpClient 对象包装了一个 NetworkStream 对象.您使用TcpClientGetStream() 方法访问NetworkStream 对象,然后使用该对象从网络读取数据和向网络写入数据.NetworkStream<的 MSDN 文章/a> 表示如下:

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:

读写操作都可以同时在一个NetworkStream 类的实例无需同步.只要有一个独特的线程对于写操作和一个读取操作的唯一线程,不会有交叉干扰在读写线程之间,没有需要同步.

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.

使用 TcpListener 对象来监听传入的连接.使用从调用 AcceptTcpClient() 返回的 TcpClient 对象与远程端点通信(读取写入).

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.

这篇关于如何使用 TcpListener 和 TcpClient 创建双工连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆