简体   繁体   English

如何在C#中找到哪个TcpClient发送了消息

[英]How to find which TcpClient had send a message in C#

I created a system to connect a series of TcpClient to a TcpListener and exchange data in a chat-like system.我创建了一个系统,将一系列 TcpClient 连接到 TcpListener 并在类似聊天的系统中交换数据。 Once the connection is established, the server adds the client to a List, and starts reading the stream waiting for messages.建立连接后,服务器将客户端添加到列表中,并开始读取流等待消息。

Once the server has received a message, is there a build-in method to know which client sent it?服务器收到消息后,是否有内置方法可以知道是哪个客户端发送的?

Alternative: I thought of attaching the client's RemoteEndPoint (Ip + port) to the message to use it as an identifier, which should be the same between the two versions of the TcpClient on the client and on the server, and unique compared to the other clients.替代方案:我想把客户端的RemoteEndPoint(Ip+端口)附加到消息上来作为一个标识符,在客户端和服务器端两个版本的TcpClient应该是一样的,并且相对于另一个是唯一的客户。 Am I right?我对吗?

Once the server has received a message, is there a build-in method to know which client sent it?服务器收到消息后,是否有内置方法可以知道是哪个客户端发送的?

Anything there is for you to add;什么可以添加的; typically you would maintain some nominal per-connection state alongside each Socket / TcpClient / TcpListener / NetworkStream / Pipe (your choice of API) instance, so that when receiving a message you can trivially look up whatever you need.通常,您会在每个Socket / TcpClient / TcpListener / NetworkStream / Pipe (您选择的 API)实例旁边维护一些名义上的每个连接状态,以便在接收消息时您可以轻松查找您需要的任何内容。 In some cases, it may be succifient to just use the Socket / TcpClient / etc instance as a key, but more often you'll have some kind of user-state/context information.在某些情况下,使用Socket / TcpClient / etc 实例作为键可能就足够了,但更多情况下,您将拥有某种用户状态/上下文信息。 This is basically entire up to you to implement.这基本上完全取决于您来实施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM