[英]Binding same EndPoint for TcpListener and TcpClient
I have a listener that listens to the localhost on an assigned portnumber like this: 我有一个监听器 ,它在分配的端口号上监听本地主机,如下所示:
TcpListener listener = new TcpListener(localIP);
listener.Start();
while (true) {
listen:
if (!listener.Pending()) {
Thread.Sleep(100);
goto listen;
}
Socket socket = listener.AcceptSocket();
}
Now the same program should make a connection to other instances of this program like this: 现在,同一个程序应该连接到该程序的其他实例,如下所示:
TcpClient client = new TcpClient(localIP); //localendpoint should use same port
client.Connect("localhost", remotePort);
As you can see I'm binding the same IPEndPoint localIP
for both the listener and client . 如您所见,我为侦听器和客户端都绑定了相同的
IPEndPoint localIP
。 So that whenever another instance of the program has a connection with this one, the socket in the listener could give me it's RemoteEndPoint
. 这样,只要程序的另一个实例与此实例建立连接,侦听器中的套接字就可以给我它的
RemoteEndPoint
。 So that I don't get a random port number generated by the system. 这样我就不会得到系统生成的随机端口号。 Of course this won't work and I get this error:
当然,这是行不通的,并且出现以下错误:
Only one usage of each socket address (protocol/network address/port) is normally permitted
通常,每个套接字地址(协议/网络地址/端口)只能使用一种
Since both listener and client are binded to the same IPEndPoint localIP
. 由于侦听器和客户端都绑定到相同的
IPEndPoint localIP
。
Is there a workaround so that I can bind a listener and client to the same EndPoint? 是否有解决方法,以便我可以将侦听器和客户端绑定到同一EndPoint? Because I want to get the portnumber from
socket.RemoteEndPoint
in the listener. 因为我想从
socket.RemoteEndPoint
中的socket.RemoteEndPoint
获取端口号。 This portnumber should be the portnumber that is assigned to each individual instance of the program. 此端口号应该是分配给程序的每个单独实例的端口号。
好吧,根据问题的评论,最好的解决方案是仅通过套接字连接发送程序正在侦听的端口号。
I recommend switching to WCF for your communications. 我建议切换到WCF进行通信。 It gives you a lot of handy tools for abstracting over serialization, the transport protocol, security, configuration, etc. Eventually, WCF lets you build service-oriented apps for a diverse client ecosystem easier than doing all the hard work yourself.
它为您提供了许多方便的工具,用于抽象化序列化,传输协议,安全性,配置等。最终,WCF使您能够比自己完成所有艰苦的工作更容易地为多种客户端生态系统构建面向服务的应用程序。
One of the features WCF has to offer is a so-called Duplex Binding , which should give you what you want: a connecting client immediately announces a way to be called back. WCF必须提供的功能之一就是所谓的Duplex Binding ,它应该为您提供所需的东西:连接的客户端会立即宣布一种回调方法。
If you still need to communicate your network topology, than you can still do so using WCF; 如果仍然需要通信网络拓扑,则仍然可以使用WCF进行通信。 And for that I recommend implementing a separate service interface that takes care of network topology exclusively.
为此,我建议实现一个单独的服务接口,该接口专门处理网络拓扑。
A tutorial + example on getting started with WCF, and creating clean code can be found here and here . 可在此处和此处找到有关WCF入门和创建干净代码的教程+示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.