Beispiel #1
0
  // Connects to server, starts a NetThread, then waits for messages.
  public static void main(String[] args) {

    int port = -1;
    String host = null;

    if (args.length >= 3) {

      name = args[0];
      host = args[1];
      try {
        port = Integer.parseInt(args[2]);
      } catch (Exception e) {
        port = -1;
      }
    }

    if (port == (-1)) {

      io.p("What server would you like to connect to? ");
      host = io.readLine();

      io.p("What port would you like to connect on? ");
      port = io.readInt();

      if ((port < 1) || (port > 65535)) {
        io.pl("Invalid port number.");
        System.exit(1);
      }
    }

    io.pl("Connecting to " + host + ":" + port + "...");

    Socket s = null;

    try {
      s = new Socket(host, port);
    } catch (Exception e) {
      io.pl("Couldn't connect to that server.");
      UIWindow.alert(null, "Couldn't connect to that server.");
      System.exit(1);
    }

    server = new NetThread(s, al, -1);

    io.pl("Connected to server.");

    Message nameMessage = new Message(Message.SET_NAME, name, null);
    server.sendMessage(nameMessage);

    while (true) {

      synchronized (al) {
        if (haveMessages()) {

          Message m = null;

          m = al.get(0);
          al.remove(0);

          handleMessage(m);

        } else {

          try {
            al.wait();
          } catch (Exception e) {
            io.pl("An exception occurred while trying to wait for messages from the server.");
            UIWindow.alert(null, "AI Client error occurred.");
            System.exit(1);
          }
        }
      }
    }
  }