Determine if server is listening when using udp(使用 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 时确定服务器是否正在侦听的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 udp 时确定服务器是否正在侦听
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01