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);
No. You are never connecting the socket, so dpsocket_receiving.isConnected()
will never be true. You don't need all that closed/open nonsense inside the read loop. The only person who is ever going to close the socket is you. The SocketTimeoutException
means that no datagram was received within the read timeout period. What you do about that is up to you, maybe nothing, but it doesn't mean you have to close and re-initialize the socket. Redoing all this won't solve an Internet connectivity problem.
The only way you will normally miss packets is if they get dropped, but closing and reopening the socket provides a window in which that will definitely occur. Don't do it.
When closing the socket, all you have to do is close it. Leaving all its multicast groups is automatic, as is disconnecting, and as you never connected it there was no need to disconnect it in the first palce.