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

查看:298
本文介绍了确定使用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天全站免登陆