Determine if server is listening when using udp

2019-08-09 19:40发布

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.

3条回答
霸刀☆藐视天下
2楼-- · 2019-08-09 19:57

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.

查看更多
相关推荐>>
3楼-- · 2019-08-09 20:08

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.

查看更多
狗以群分
4楼-- · 2019-08-09 20:09

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.

查看更多
登录 后发表回答