使用 udp 时确定服务器是否正在侦听 [英] Determine if server is listening when using udp

查看:31
本文介绍了使用 udp 时确定服务器是否正在侦听的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

为了做到这一点,connect() 方法首先需要检查监听服务器.a) 第一次发生这种情况时,没有找到服务器,调用 connect() 的一方开始监听 localhost 和配置的传入端口联系.b) 调用 connect() 的第二方也会检查给定端口上的远程主机,识别服务器并连接到它.

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.

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

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.

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

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

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

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

推荐答案

使用 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.

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

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.

这篇关于使用 udp 时确定服务器是否正在侦听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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