FileDocCategorySizeDatePackage
ChessEventServer.javaAPI DocExample2649Tue Jan 20 21:45:56 GMT 1998dcj.examples.message

ChessEventServer

public class ChessEventServer extends EventTransceiver
Source code from "Java Distributed Computing", by Jim Farley. Class: ChessEventServer Example: 6-15 Description: The chess server re-implemented as an event-based communication agent.

Fields Summary
ChessPlayer
player
Constructors Summary
public ChessEventServer(String host, int port)


       
    super(host, port);
    register();
  
public ChessEventServer(InetAddress host, int port)

    super(host, port);
    register();
  
Methods Summary
public voidhandleEvent(java.util.EventObject e)

    try {
      if (e instanceof ChessMoveEvent) {
        ChessMoveEvent cm = (ChessMoveEvent)e;
        ChessMove m = cm.getMove();
        switch (cm.getType()) {
          case ChessMoveEvent.SUBMIT:
            if (player.acceptMove(m)) {
              ChessMoveEvent conf = new ChessMoveEvent(m, player);
              conf.setConfirm();
              sendEvent(conf);

              ChessMove next = player.nextMove();
              if (next != null) {
                ChessMoveEvent submit = new ChessMoveEvent(next, player);
                sendEvent(submit);
              }
              else {
                sendEvent(new ChessConcedeEvent(player));
              }
            }
            else {
              ChessMoveEvent reject = new ChessMoveEvent(m, player);
              reject.setReject();
              sendEvent(reject);
            }
          break;

          case ChessMoveEvent.REJECT:
            ChessMove next = player.nextMove();
            if (next != null) {
              sendEvent(new ChessMoveEvent(next, player));
            }
            else {
              sendEvent(new ChessConcedeEvent(player));
            }
          break;

          case ChessMoveEvent.CONFIRM:
            player.moveAccepted(m);
          break;
        }
      }
      // If we get a concede message, the other player has
      // given up and we win...
      else if (e instanceof ChessConcedeEvent) {
        player.conceded();
      }
    }
    catch (IOException ioe) {
      System.out.println("IO error while handling event.");
      ioe.printStackTrace();
    }
  
voidregister()

    // Add ourselves to this handler's list for
    // chess-related events
    try {
      addHandler(this, Class.forName("ChessMoveEvent"));
      addHandler(this, Class.forName("ChessConcedeEvent"));
    }
    catch (ClassNotFoundException nfe) {}