使用udp时确定服务器是否正在监听

发布于 2024-11-03 18:02:09 字数 598 浏览 1 评论 0原文

设置:我想编写一个点对点Connection类,该类在使用时不区分服务器和客户端。第一个调用 connect() 的主机将成为等待客户端连接的服务器,第二个主机将成为连接到服务器的客户端。

为此,connect() 方法首先需要检查侦听服务器。 a) 第一次发生这种情况时,找不到服务器,并且调用 connect() 的一方开始侦听 localhost 以及配置的传入端口联系。 b) 调用 connect() 的第二方还会检查给定端口上的远程主机,识别服务器并连接到它。

使用 TCP 这并不太难,因为当无法建立连接时,TcpClient.Connect() 会引发异常。因此我知道我什么时候是第一个。然而,由于我只使用可靠的 LAN,所以我想使用 UDP。

我的问题:如何确定 UDP 服务器套接字是否正在等待传入数据。

理想情况下,我想随后直接使用异步网络 API。而不是我自己处理监听线程。

The setting: I want to write a point-to-point Connection class that, when used, does not differentiate between server and client. The first host which calls connect() shall become the server waiting for the client to connect and the second shall become the client that connects to the server.

In order to do that the connect() method first needs to check for a listening server. a) The first time this happens no server is found and the party calling connect() starts listening on localhost and the configured port for an incoming connection. b) The second party calling connect() also checks the remote host on the given port, recognizes the server and connects to it.

This is not too hard using TCP since TcpClient.Connect() throws an exception when no connection could be established. Therefore I know when I'm the first. Since I use reliable LAN only, I wanted to use UDP, however.

My problem: How can I determine whether an UDP server socket is waiting for incoming data.

Ideally I would like to use the asynchronous network API directly afterwards. Instead of dealing with listening threads all by myself.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

残月升风 2024-11-10 18:02:11

我认为您无法检查侦听服务器,除非发送数据包并等待查看是否收到答复。

I don't think you can check for a listening server, short of sending a packet and waiting to see if you get a reply.

淡淡绿茶香 2024-11-10 18:02:10

对于 UDP,通信模型类似于瓶中消息:您知道您发送了它,但无法知道是否有人收到过它。

您需要手动建立通信协议来确定远程方是否正在侦听(例如让他们发送“是的,我在这里”响应)。这需要两个端点都接受UDP数据报。

With UDP, the communication model is akin to a message in a bottle: you know you sent it, but there's no way to know if anyone ever received it.

You need to manually establish a communication protocol to determine if the remote party is listening (e.g. have them send a "Yes, I 'm here" response). This would require both endpoints to accept UDP datagrams.

归途 2024-11-10 18:02:10

正如 Jon 和 Andrew 所说,您无法查看侦听器是否打开,但您可以实现 ping/pong 协议。如果没有返回 ping,请在第一次连接时发送 ping,然后将其设置为服务器。
如果你回来了,那就是你的服务器。

As Jon and Andrew said you can't see if a listener is open, but you can implement a ping/pong protocol. Send a ping first time you connect if no pong back then set this up like a server.
If you got pong back then that's your server.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文