コード例 #1
0
 @Override
 protected void onExit() {
   if (isHost) {
     server.stop();
   } else {
     client.disconnect();
   }
 }
コード例 #2
0
  private void initNetworking() {
    if (isHost) {
      server.addParser(RequestMessage.class, data -> requestQueue.offer(data));
      server.addParser(String.class, data -> isConnected = true);
      server.start();
    } else {
      client.addParser(DataMessage.class, data -> updateQueue.offer(data));

      try {
        client.connect();
        client.send("Hi");
      } catch (Exception e) {
        log.severe(FXGLLogger.errorTraceAsString(e));
        exit();
      }
    }
  }
コード例 #3
0
  @Override
  protected void onUpdate(long now) {
    if (isHost) {
      if (!isConnected) return;

      RequestMessage data = requestQueue.poll();
      if (data != null) {
        for (KeyCode key : data.keys) {
          if (key == KeyCode.W) {
            player2.translate(0, -5);
          } else if (key == KeyCode.S) {
            player2.translate(0, 5);
          } else if (key == KeyCode.A) {
            player2.translate(-5, 0);
          } else if (key == KeyCode.D) {
            player2.translate(5, 0);
          } else if (key == KeyCode.ESCAPE) {
            exit();
          }
        }
      }

      try {
        server.send(
            new DataMessage(
                player1.getTranslateX(),
                player1.getTranslateY(),
                player2.getTranslateX(),
                player2.getTranslateY()));
      } catch (Exception e) {
        log.warning("Failed to send message: " + e.getMessage());
        exit();
      }
    } else {
      DataMessage data = updateQueue.poll();
      if (data != null) {
        player1.setPosition(data.x1, data.y1);
        player2.setPosition(data.x2, data.y2);
      }

      KeyCode[] codes =
          keys.keySet()
              .stream()
              .filter(k -> keys.get(k))
              .collect(Collectors.toList())
              .toArray(new KeyCode[0]);

      try {
        client.send(new RequestMessage(codes));

        if (keys.get(KeyCode.ESCAPE)) {
          exit();
        }
      } catch (Exception e) {
        log.warning("Failed to send messsage: " + e.getMessage());
        exit();
      }

      keys.forEach((key, value) -> keys.put(key, false));
    }
  }