Example #1
0
 private synchronized void sendMessage(BoggleMessage m) {
   try {
     if (out != null) {
       out.write(m.toString());
       out.write('\n');
       out.flush();
     }
   } catch (java.io.IOException e) {
     displayText("Cannot contact server.");
   }
 }
Example #2
0
 public void run() {
   if (port < 0 || port > 65535) {
     displayText("Invalid port number [0..65535].");
     bye();
     return;
   }
   synchronized (this) {
     try {
       socket = new Socket(hostname, port);
       socket.setKeepAlive(true);
     } catch (java.net.UnknownHostException e) {
       displayText("Unknown host: " + hostname);
       bye();
       return;
     } catch (java.net.ConnectException e) {
       displayText("Connection refused by server.");
       bye();
       return;
     } catch (java.io.IOException e) {
       displayText("Cannot create socket.");
       bye();
       return;
     }
     try {
       out = new OutputStreamWriter(socket.getOutputStream());
       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     } catch (java.io.IOException e) {
       displayText("Cannot open socket streams.");
       bye();
       return;
     }
   }
   sendMessage(new BoggleMessage(BoggleMessage.Type.JOIN, getName()));
   displayText(hostname + " successfully contacted.");
   while (!socketClosed()) {
     String line;
     try {
       line = in.readLine();
     } catch (java.io.IOException e) {
       line = null;
     }
     if (line == null) {
       break;
     }
     BoggleMessage m;
     try {
       m = BoggleMessage.parse(line);
     } catch (BoggleMessage.Exception e) {
       e.printStackTrace();
       displayText("Incoherent message from server.  Quitting.");
       here("Message was " + line);
       bye();
       break;
     }
     if (m.type == BoggleMessage.Type.TEXT) {
       displayText(m.body);
       continue;
     }
     if (m.type == BoggleMessage.Type.BOARD) {
       Matcher ma = BOARD.matcher(m.body);
       if (ma.matches())
         try {
           int w = Integer.parseInt(ma.group(1));
           int h = Integer.parseInt(ma.group(2));
           displayBoard(w, h, ma.group(3).toCharArray());
           continue;
         } catch (NumberFormatException e) {
         }
       displayText("Cannot parse board from server.  Quitting.");
       bye();
       break;
     }
   }
 }