/** * PacketReceivingThread.java */ package boondock.holdem.Network; import java.io.*; import java.net.*; import java.util.*; /** * Listens for DatagramPackets containing messages. * * @author Jonathan O'Keefe * @author Scott Semonian * @author Matt Brinza * @author Hamid R. Tahsildoost * * @author The Boondock Saints * @author No Limit Texas Holdem */ public class PacketReceivingThread extends Thread { private MessageListener messageListener; private MulticastSocket multicastSocket; private InetAddress multicastGroup; private boolean keepListening = true; /** * PacketReceivingThread constructor. * * @param listener Sets the MessageListener to whom message should be delivered */ public PacketReceivingThread( MessageListener listener ){ super( "PacketReceivingThread" ); messageListener = listener; try { multicastSocket = new MulticastSocket(constants.MULTICAST_LISTENING_PORT ); multicastGroup = InetAddress.getByName(constants.MULTICAST_ADDRESS ); multicastSocket.joinGroup( multicastGroup ); multicastSocket.setSoTimeout( 5000 ); } catch ( IOException ioException ) { System.out.println("IO Exception Occured in PacketReceivingThread"); //ioException.printStackTrace(); } } // end PacketReceivingThread constructor /** * Listen for new messages from the mutlicast group and fwd them to the MessageListener. * This function is NOT synchronized; causes hang on disconnect. */ public void run(){ while ( keepListening ) { byte[] buffer = new byte[ constants.MESSAGE_SIZE ]; DatagramPacket packet = new DatagramPacket( buffer,constants.MESSAGE_SIZE ); try { multicastSocket.receive( packet ); } catch ( InterruptedIOException interruptedIOException ) { //System.out.println("InterruptedIOException Occured while running PacketReceivingThread"); continue; } catch ( IOException ioException ) { System.out.println("IOException Occured while running PacketReceivingThread"); //ioException.printStackTrace(); break; } String message = new String( packet.getData() ); message = message.trim(); StringTokenizer tokenizer = new StringTokenizer(message, constants.MESSAGE_SEPARATOR ); if ( tokenizer.countTokens() == 2 ) messageListener.messageReceived(tokenizer.nextToken(),tokenizer.nextToken() ); // message body } // end while try { multicastSocket.leaveGroup( multicastGroup ); multicastSocket.close(); } catch ( IOException ioException ) { System.out.println("IOException Occured while running PacketReceivingThread (Multicast Socket)"); //ioException.printStackTrace(); } } // end method run /** * Stop listening for new messages. * This function is synchronized. */ public synchronized void stopListening(){ keepListening = false; } } // end class PacketReceivingThread