I am working on a UDP based socket apps, and here I got some questions on how to implement the listen function on receive side
Is below a good way to let the receive side socket to keep listen the server side? Suppose I don't know when will the server side will send the packet to receive side, so I need to keep the receive function always on. Will it miss or some how break the while(true) loop? If yes, how to "reconnect" and make the listen loop alive again?
while(true){ try{ if ( udpsocket_receiving.isClosed() || !udpsocket_receiving.isConnected() ) { serverAddress = InetAddress.getByName(SERVERIP); udpsocket_receiving = new MulticastSocket(SERVERPORT) ; udpsocket_receiving.joinGroup(serverAddress); udpsocket_receiving.setSoTimeout(10000); } udpsocket_receiving.receive(recpacket); // Block of code to do with the packet } catch ( SocketTimeoutException e ) { // What suppose to do here if I catch this exception? } finally { udpsocket_receiving.close(); continue; } }
Can above method already solve if I don't have Internet access for certain time, suppose the method will always catch to the SocketTimeoutException right? But when the Internet access resume later, can I still keep listen when packet comes?
Suppose I got the first packet from sender side, and executing the code, but sender side send a second packet on that time, will I miss the packet? Since the while loop on the first packet is not end.
Is below a good approach to manually close the socket and "reconnect' it again? Will it somehow bind the port and can not use that same port to new a object again? And if this is block of correct code, should I put those inside the
SocketTimeoutException
in question one?udpsocket_receiving.leaveGroup(serverAddress); udpsocket_receiving.disconnect(); udpsocket_receiving.close(); udpsocket_receiving = new MulticastSocket(SERVERPORT) ; udpsocket_receiving.setSoTimeout(10000); udpsocket_receiving.joinGroup(serverAddress);