Dynamic Socket Connection
I am in the process of writing a remote multi-player game. So far, my design holds that when a client is started, a GUI is created and then tries to connect to the game server. If the game server is available, the client falls into an infinite loop using BufferedReader to get commands from the server that instruct the GUI on state changes. If the game server is not available, the client quits with an appropriate message.
As an improvement, I want to be able to start the client GUI and then instruct it to connect to/disconnect from/reconnect to the game server via menu selection. The problem I run into here is that the client falls into the infinite loop immediately after the menu selection is made. This prevents the client GUI from 'cleaning up' the drop down menu and repainting the JFrame, as well as bocking the event listeners. Basically, the client freezes and fails to take any more input.
In the first approach, I perform the socket connection and fall into the loop inside my constructor. In the second approach, I relocate these functions to a method. I know that this is a pretty basic way to do things, does anyone have a suggestion on a more elegant approach?
code:
public ClientFace(){//Define constructor
super("Remote-Game");
table =new Table(this);//Create game table panel
menu =new Menu(table);//Create new menu
u =new MyUtil();
u.debug();
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add("North", menu);//Add menu to frame
getContentPane().add("Center", table);//Add table panel to frame
sizeFrame();
mode = Listen;
String fromServer =null;
try{
clientSocket =new Socket("localhost", 7111);
serverOut =new PrintWriter(clientSocket.getOutputStream(),true);
serverIn =new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (active){
u.trace("waiting to read from server");
if ((fromServer = serverIn.readLine()) !=null){// Always listen for instructions from the server
processServerInstruction(fromServer);
}
}
serverOut.close();
serverIn.close();
clientSocket.close();
}
catch (ConnectException ce){
u.out("!! The connection has been refused\n!! Please make sure the server is running");
System.exit(1);
}
catch (Exception e){
u.err(e);
System.exit(1);
}
}

