Example #1
0
  // Called when an established peer sends us a message
  private void processPeerMessage(SocketChannel c) throws IOException {
    Peer peer = peers.get(c);

    ByteBuffer b = ByteBuffer.allocateDirect(1);
    int read = c.read(b);
    if (read < 0) {
      c.close();
      return;
    }
    if (read < 1) return; // No data?
    b.flip();
    byte type = b.get();

    switch (type) {
      case MSG_DEBUG:
        log(peer.getName() + ": " + ChannelHelper.getString(c));
        break;
      case MSG_BALL:
        int id = ChannelHelper.getInt(c);
        double position = ChannelHelper.getDouble(c);
        double dx = ChannelHelper.getDouble(c);
        double dy = ChannelHelper.getDouble(c);
        int D = ChannelHelper.getInt(c);
        if (listener != null) listener.receiveBall(id, position, dx, dy, D);
        break;
        //		Dropped ball
        //			Informative to all peers & server
        //			(Maybe implement as passing ball to server?)
        //			Server may respond with “you lose”
        //		Drop player
        //			Paxos confirmation that client is gone
        //		Heartbeat?
        //			Probably only sent in response to drop
        //			Ping/pong messages
        //		Server failure
        //			All peers, send choice of backup
      default:
        System.err.println("Unknown peer message: " + type);
    }
  }