简体   繁体   English

具有交叉通信要求的C#TCP服务器和客户端

[英]C# TCP server and client with cross-communication requirement

I need some feedback with some programming logic. 我需要一些编程逻辑的反馈。

I'm developing a TCP Server using C#, which will also act as a TCP client. 我正在使用C#开发TCP服务器,该服务器还将充当TCP客户端。 Basically, a client device (A) contacts my TCP Server and sends information. 基本上,客户端设备(A)与我的TCP Server联系并发送信息。 Based on that the TCP server may (or may not) talk to another server (Z) over TCP, send some data to it and sometimes get a response which it passes back to device A. So far so good, this works quite well. 基于此,TCP服务器可以(或可以不)通过TCP与另一台服务器(Z)进行通信,向其发送一些数据, 有时还获得响应,并将其传递回设备A。到目前为止,效果很好。 However, sometimes Z creates a new connection to my C# TCP server, and wants to send some data to device A. 但是,有时Z创建与我的C#TCP服务器的新连接,并希望将一些数据发送到设备A。

This is what I am struggling with. 这就是我在努力的目标。 I can get the data from Z, read it and see the destination IP address in the text that is read. 我可以从Z中获取数据,进行读取,然后在读取的文本中查看目标IP地址。 But how do I send that to device A, which is still connected via a TCPListener on it's own thread? 但是,如何将其发送到仍通过其自己线程上的TCPListener连接的设备A?

I could use static variables and the "lock" mechanism to have the thread look for something to send to the device, but what happens if I add device B & C as well? 我可以使用静态变量和“锁定”机制让线程寻找要发送到设备的东西,但是如果我还添加设备B和C,会发生什么情况?

I basically need some way of, based on the data sent from Z on a new connection, determining which TCPListener on which thread the data should be sent to the devices. 我基本上需要某种方式,基于从Z在新连接上发送的数据,确定应在哪个线程上的哪个TCPListener上将数据发送到设备。

It's doing my head in so any links you may have or rough logic (doesn't have to be code) would greatly help. 这让我很忙,所以您可能拥有的任何链接或粗略的逻辑(不必是代码)都将极大地帮助您。

And yes, I've been searching Google for a while, but all the examples I have found are simpler than what I need to do. 是的,我搜索Google已有一段时间了,但是我发现的所有示例都比我要做的要简单。

Thanks in advance! 提前致谢!

you can keep a Dictionary<IPAddress,TCPClient> for this purpose and send the message to the destination IP. 您可以为此保留一个Dictionary<IPAddress,TCPClient>并将消息发送到目标IP。 Make sure you handle the multiple clients from the single IP gracefully either by droping the previous connection while accepting new one or instead having Dictionary<IPAddress,List<TCPClient>> 确保通过接受新连接的同时Dictionary<IPAddress,List<TCPClient>>先前的连接,或者改为使用Dictionary<IPAddress,List<TCPClient>>来优雅地处理单个IP的多个客户端。

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

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