Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining a bidirectional UDP connection

I'm writing an Android UDP client that connects to and communicates bidirectionally (with no relationship between sent and received messages) with a Windows server. Once the initial Datagram has been sent to the server I want to be able to send data in either direction at any time. My questions are:

1) Is it correct to keep the initial socket open and use it for both sending and receiving ?

2) Should I send and receive in the same thread (with a timeout on receive) or in separate threads (allowing the receive to block) ?

3) Will the socket automatically close if data is not sent / received within a certain interval ?

like image 424
Funky Oordvork Avatar asked Jan 14 '23 18:01

Funky Oordvork


1 Answers

  1. Yes, that is no problem and is the most convenient way to deal with the bidirectional communication. Also, if the client is placed behind a NAT, it is required for the hole punching to work correctly. Even though you bind to the same IP and port on the client, you are not guaranteed to get the same mapping in the NAT. Thus, the server might not be able to reach the client. Remember that these mappings time out and are initiated from inside the NAT'ed network, so some probing might be needed if the client is idle for a long time.

  2. That is up to how you design the application, but there is no problem doing so. Just monitor both the read and write status of the socket using for example select. If you create a non-blocking socket combined with a read/write-queue, you are sure never to block operation. As UDP either writes everything or nothing, the queue's are quite straight-forward.

  3. Based on my experience, that is vendor-specific on Android. Some phones keep sockets open for a long time, while others close them after a certain idle-period. All phones seem to close sockets when the device goes to sleep (the state when the power button is pressed), except those associated with a background task.

like image 142
Kristian Evensen Avatar answered Jan 21 '23 07:01

Kristian Evensen