/** * SocketMessageManager.java */ package boondock.holdem.Network; import java.util.*; import java.net.*; import java.io.*; import javax.swing.*; /** * SocketMessageManager communicates with the server via sockets * * @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 SocketMessageManager implements MessageManager { private Socket clientSocket; private String serverAddress; private PacketReceivingThread receivingThread; private boolean connected = false; private static JFrame frame; /** * SocketMessageManager constructor. * * @param address The address of the server to connect to. */ public SocketMessageManager( String address ) { serverAddress = address; } /** * Connects to the server and sends initial connect message to the active MessageListener * This function is synchronized. * * @param listener The active/given MessageListener. * @param userConnectingName The ID of the user connecting to the server. */ public synchronized void connect( MessageListener listener, String userConnectingName ) { if ( connected ) return; try { clientSocket = new Socket( InetAddress.getByName( serverAddress ), constants.SERVER_PORT ); receivingThread = new PacketReceivingThread( listener ); receivingThread.start(); connected = true; } catch ( IOException ioException ) { //ioException.printStackTrace(); JOptionPane.showMessageDialog(frame, "There is no server running at this IP address at the current time"); System.exit( 0 ); } } // end method connect /** * Disconnect from the server and unregister the given MessageListener * This function is synchronized. * * @param listener The active/given MessageListener. */ public synchronized void disconnect( MessageListener listener ) { if ( !connected ) return; try { Thread disconnectThread = new SendingThread( clientSocket, "", constants.DISCONNECT_STRING ); disconnectThread.start(); disconnectThread.join( 10000 ); receivingThread.stopListening(); clientSocket.close(); } // end try catch ( IOException ioException ) { System.out.println("IOException Occured while disconnecting user."); //ioException.printStackTrace(); } catch ( InterruptedException interruptedException ) { System.out.println("InterruptedIOException Occured while disconnecting user."); //interruptedException.printStackTrace(); } connected = false; } // end method disconnect /** * Send message, using data parameters, via a SendingThread. * This function is synchronized. * * @param from User name of the sender of the message. * @param message The message that the sender is sending. */ public synchronized void sendMessage( String from, String message ) { if ( !connected ) return; new SendingThread( clientSocket, from, message).start(); } } // end method SocketMessageManager