从一个TcpClient检索多个套接字 [英] retrieving multiple sockets from one TcpClient

查看:62
本文介绍了从一个TcpClient检索多个套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我与1个TcpClient建立了2个连接,是否可以从该TcpClient中检索2个不同的套接字?此时,只要第二次连接并从客户端获取Socket,套接字似乎就会因第一次连接而丢失,因为我无法再通过该套接字发送或接收。



我使用以下代码从客户端检索套接字。



If I have 2 connections being made to 1 TcpClient, is it possible to retrieve 2 different sockets from that one TcpClient? At the moment, as soon as the second connection is being made and getting the Socket from the client, the socket seems to get lost with the first connection, as I cannot send or receive over that socket anymore.

I am using the following code to retrieve the socket from the client.

Socket socket = _tcpClient.Client;

推荐答案

您无法从一个客户端建立多个连接。

TCP是面向连接的,所以多重性总是1:1(服务器套接字:客户端套接字)。



你应该使用两个TcpClients进行两个连接。
You cannot establish multiple connections from one client.
TCP is connection orientated, so the multiplicity is always 1:1 (Server-Socket : Client-Socket).

You should use two TcpClients for two connections.


您需要创建另一个客户端实例。 Henning描述的比例为1:1,因此您需要的每个实例都需要与您将拥有的连接一样多。
You need to create another instance of the client. The ratio is 1 : 1 as Henning described, so you need as many instances on each side as connections you will have.


您需要建立两个连接(或任何其他数量的连接)您可能需要)使用两个单独的 TcpClient 实例,它基本上是 Socket 实例的包装器。此外,您可以在 Socket 对象或 TcpListener / TcpClient 对象的级别进行开发。您可以在一个项目或解决方案中混合使用这两种方法,但在大多数情况下,不需要它。这些方法非常接近, TcpListener / TcpClient 方法只是一小部分更高级别,由.NET FCL提供,为了一些额外的便利。



-SA
You would need to make two connections (or any other number of connections you may need) using two separate instances of TcpClient, which is, basically, a wrapper around an instance of a Socket. Besides, you can do development either on the level of Socket objects, or TcpListener/TcpClient objects. You can mix both approaches in one project or solution, but in most cases there is no need for it. Those approaches are very close, with TcpListener/TcpClient approach being just a tiny bit of higher level, provided by .NET FCL for some extra convenience.

—SA


这篇关于从一个TcpClient检索多个套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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