예제 #1
0
  /**
   * Used whenever a player exits from the game. The most recent information stored for the player
   * will be saved into the database and any ties with the server will be removed as well.
   */
  public void removePlayerData() {
    if (activeObjects.containsKey(Lobby.class)) {
      LobbyManager.getInstance().removeUser(getActiveObject(Lobby.class), player.getID());
    }

    try {
      player.getSaveTimer().finish();
      PlayerDAO.updateLogout(player.getID());
    } catch (SQLException ex) {
      Log.println_e(ex.getMessage());
    }

    GameServer.getInstance().removeActivePlayer(player.getID());

    ResponseExitGame responseExitGame = new ResponseExitGame();
    responseExitGame.setUserID(player.getID());
    NetworkManager.addResponseForAllOnlinePlayers(player.getID(), responseExitGame);

    ResponseChat responseChat = new ResponseChat();
    responseChat.setMessage("[" + player.getUsername() + "] has logged off.");
    NetworkManager.addResponseForAllOnlinePlayers(player.getID(), responseChat);

    ResponseGetPlayers responsePlayers = new ResponseGetPlayers();
    responsePlayers.setPlayers(GameServer.getInstance().getActivePlayers());
    NetworkManager.addResponseForAllOnlinePlayers(player.getID(), responsePlayers);

    Log.printf("User '%s' has logged off.", player.getUsername());
  }
예제 #2
0
 /**
  * Create a game server database instance of the choosen game
  *
  * @throws JSONException
  */
 public void createGameServer() throws JSONException {
   GameServer gameServer = getGameServer();
   if (null != gameServer) {
     gameServer.initiate();
     gameServer.commit();
   }
 }
예제 #3
0
 public void trySaveFavourites() {
   try {
     try (PrintWriter writer = new PrintWriter("favourites.txt", "UTF-8")) {
       for (GameServer s : favourites) {
         writer.println(s.getIp() + ":" + s.getPort());
       }
     }
   } catch (FileNotFoundException | UnsupportedEncodingException ex) {
     System.err.println(" - Couldn't save favourites");
   }
 }
예제 #4
0
  public GameApplication(
      Game game,
      boolean multiplayer,
      String joinAdress,
      String playerId,
      int playerNumber,
      String map) {
    this.game = game;
    this.map = map;

    setPauseOnLostFocus(false);
    setShowSettings(false);

    if (joinAdress.isEmpty()) {
      server = new GameServer();
      if (server.isStarted() == false) {
        System.out.println("Error cannot start server");
        System.exit(0);
      }

      joinAdress = "localhost";
    }

    if (multiplayer) {
      try {
        client = new GameClient(game, joinAdress, playerId, playerNumber);
      } catch (Exception e) {
        if (server != null) {
          server.close();
          System.out.println("Client error " + e.getMessage());
          System.exit(0);
        }
      }
    }

    try {
      FileInputStream fis = new FileInputStream(new File("settings.txt"));
      AppSettings settings = new AppSettings(true);
      settings.load(new BufferedInputStream(fis));
      setSettings(settings);
    } catch (Exception e) {
      AppSettings settings = new AppSettings(true);
      settings.setResolution(1024, 768);
      settings.setFrameRate(50);
      settings.setFullscreen(false);
      settings.setTitle("JPenguin");

      setSettings(settings);
    }
  }
예제 #5
0
  @Test
  public void testCreateRoomByUser() {
    when(service.getUserBySession(anyString())).thenReturn(null);
    Room endRoom = gameServer.createRoom("aaa", "aaa", null);
    assertNull(endRoom);

    Room room = new RoomFFA("aaa");
    UserProfile profile = spy(new UserProfile("aa", "bb"));
    when(service.getUserBySession(anyString())).thenReturn(profile);
    when(profile.getCurrentroom()).thenReturn(room);

    endRoom = gameServer.createRoom("aaa", "aaa", null);
    assertNull(endRoom);
  }
  @Test
  public void testPlayerInfoSourceAuthenticated() throws Exception {
    String status = this.readFixture("status_source");

    SteamPlayer user1 = mock(SteamPlayer.class);
    SteamPlayer user2 = mock(SteamPlayer.class);
    HashMap<String, SteamPlayer> playerMap = new HashMap<String, SteamPlayer>();
    playerMap.put("12345678123456789", user1);
    playerMap.put("99999999999999999", user2);
    this.server.playerHash = playerMap;
    this.server.rconAuthenticated = true;

    doNothing().when(this.server).handleResponseForRequest(GameServer.REQUEST_PLAYER);
    when(this.server.rconExec("status")).thenReturn(status);

    HashMap<String, String> user1Data = new HashMap<String, String>();
    user1Data.put("name", "user1");
    user1Data.put("id", "12345678123456789");
    user1Data.put("time", "4449s");
    user1Data.put("ping", "300");
    user1Data.put("addr", "11.2.333.44");
    HashMap<String, String> user2Data = new HashMap<String, String>();
    user2Data.put("name", "user2");
    user2Data.put("id", "99999999999999999");
    user2Data.put("time", "50s");
    user2Data.put("ping", "45");
    user2Data.put("addr", "192.192.192.192");

    mockStatic(GameServer.class);
    ArrayList<String> attributes = new ArrayList<String>();
    // Won't read data about a player if no attributes were found
    attributes.add("someAttribute");
    when(GameServer.getPlayerStatusAttributes(
            "id                name                                  ping  connected   addr"))
        .thenReturn(attributes);
    when(GameServer.splitPlayerStatus(
            attributes,
            "12345678123456789 \"user1\"                               300   4449s       11.2.333.44"))
        .thenReturn(user1Data);
    when(GameServer.splitPlayerStatus(
            attributes,
            "99999999999999999 \"user2\"                               45    50s         192.192.192.192"))
        .thenReturn(user2Data);

    this.server.updatePlayers("password");

    verify(user1).addInformation(user1Data);
    verify(user2).addInformation(user2Data);
  }
예제 #7
0
 public void joinServer(GameServer server, boolean jk2) throws IOException {
   String path =
       jk2
           ? settingsManager.getSetting(Setting.JK2PATH)
           : settingsManager.getSetting(Setting.JKAPATH);
   String strIp = server.getIp();
   ProcessBuilder builder =
       new ProcessBuilder(
           path,
           "+connect",
           strIp.substring(strIp.indexOf("/") + 1, strIp.length()) + ":" + server.getPort());
   builder.directory(new File(path.substring(0, path.lastIndexOf("/"))));
   builder.redirectErrorStream(true);
   Process process = builder.start();
 }
예제 #8
0
 @Test
 public void testJoinRoomNoRoom() {
   when(service.getUserBySession(anyString())).thenReturn(new UserProfile("aa", "bb"));
   when(rooms.containsKey(anyString())).thenReturn(false);
   Room room = gameServer.joinRoom("aa", "aa", "aa");
   assertNull(room);
 }
예제 #9
0
  public void newSession() {
    session_id = GameServer.createUniqueID();
    updates.clear();

    player = null;
    avatar = null;
  }
예제 #10
0
  @Test
  public void isCorrectPlayerInGameNoPlayer() {
    when(service.isAuthorized(anyString())).thenReturn(true);
    when(service.getUserBySession(anyString())).thenReturn(null);

    assertFalse(gameServer.isCorrectPlayerInGame("aa"));
  }
예제 #11
0
  public static void main(String[] args) {
    ExecutorService executor = Executors.newCachedThreadPool();
    DbManager.init();
    parseArguments(args);

    GameServer.getInstance();

    while (true) {

      try {
        // establish server socket
        s = new ServerSocket(socketPort);

        // wait for incoming connection
        incoming = s.accept();

        executor.execute(new Session(incoming));

      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }

      try {
        s.close();
        s = null;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
예제 #12
0
 @Before
 public void setUp() {
   new ProjectDB().initBD("hibernate-test.cfg.xml");
   service = mock(AccountService.class);
   rooms = spy(new HashMap<>());
   gameServer = new GameServer(service);
   gameServer.setRooms(rooms);
 }
예제 #13
0
  @Test
  public void testJoinRoomUserPassToRoom() {
    UserProfile profile = spy(new UserProfile("aa", "bb"));
    when(service.getUserBySession(anyString())).thenReturn(profile);
    when(rooms.containsKey(anyString())).thenReturn(true);
    when(profile.getCurrentroom()).thenReturn(null);
    Room room = new RoomFFA("aaa", "cc");
    when(rooms.get(anyString())).thenReturn(room);

    Room endRoom = gameServer.joinRoom("aaa", "", "aa");

    assertNull(endRoom);

    endRoom = gameServer.joinRoom("aa", null, "aa");

    assertNull(endRoom);
  }
예제 #14
0
 public boolean flagClientForRemoval(int id) {
   boolean result = false;
   synchronized (this) {
     clientConnections.put(id, null);
   }
   server.flagCarForRemoval(id);
   return result;
 }
예제 #15
0
  @Test
  public void testIsGameReady() throws Exception {
    UserProfile profile = new UserProfile("test", "test");

    Room room = new RoomFFA("testRoom");
    room.addUser(profile);
    profile.setCurrentroom(room);

    doReturn(profile).when(service).getUserBySession(anyString());

    assertFalse(gameServer.isGameReady(anyString()));

    UserProfile profile1 = new UserProfile("test1", "test1");
    room.addUser(profile1);

    assertTrue(gameServer.isGameReady(anyString()));
  }
예제 #16
0
  @Test
  public void testGetPlayerRoomBySession() throws Exception {
    UserProfile profile = new UserProfile("test", "test");
    Room room = new RoomFFA("testRoom");
    room.addUser(profile);
    profile.setCurrentroom(room);

    when(service.getUserBySession(anyString())).thenReturn(profile);

    Room testingRoom = gameServer.getPlayerRoomBySession(anyString());

    assertNotNull(testingRoom);
    assertTrue(testingRoom.checkUser(profile));

    when(service.getUserBySession(anyString())).thenReturn(null);

    assertNull(gameServer.getPlayerRoomBySession(anyString()));
  }
예제 #17
0
  @Test
  public void testIsCorrectPlayerInGameAlready() throws Exception {
    when(service.isAuthorized(anyString())).thenReturn(true);
    UserProfile profile = new UserProfile("test", "test");
    Room room = new RoomFFA("testRoom");
    profile.setCurrentroom(room);
    when(service.getUserBySession(anyString())).thenReturn(profile);

    assertTrue(gameServer.isCorrectPlayerInGame("aa"));
  }
예제 #18
0
  @Test
  public void testCreateRoomAlreadyExist() {
    UserProfile profile = spy(new UserProfile("aa", "bb"));
    when(service.getUserBySession(anyString())).thenReturn(profile);
    when(profile.getCurrentroom()).thenReturn(null);
    when(rooms.containsKey(anyString())).thenReturn(true);

    Room room = gameServer.createRoom("aaa", "aaa", null);

    assertNull(room);
  }
  @Test
  public void testHandleChallengeRequests() throws Exception {
    S2C_CHALLENGE_Packet packet = mock(S2C_CHALLENGE_Packet.class);
    when(packet.getChallengeNumber()).thenReturn(1234);
    when(server.getReply()).thenReturn(packet);

    this.server.handleResponseForRequest(GameServer.REQUEST_CHALLENGE);

    assertEquals(1234, this.server.challengeNumber);
    verify(this.server).sendRequest(any(A2S_PLAYER_Packet.class));
  }
예제 #20
0
 public boolean addClient(int id, ClientConnection conn, Car car) {
   boolean success = false;
   synchronized (this) {
     if (clientConnections.get(id) == null) {
       server.addCar(id, car);
       clientConnections.put(id, conn);
       success = true;
     }
   }
   return success;
 }
  @Test
  public void testHandleRulesRequests() throws Exception {
    S2A_RULES_Packet packet = mock(S2A_RULES_Packet.class);
    HashMap<String, String> rulesMap = new HashMap<String, String>();
    rulesMap.put("test", "test");
    when(packet.getRulesHash()).thenReturn(rulesMap);
    when(server.getReply()).thenReturn(packet);

    this.server.handleResponseForRequest(GameServer.REQUEST_RULES);

    assertEquals("test", this.server.rulesHash.get("test"));
    verify(this.server).sendRequest(any(A2S_RULES_Packet.class));
  }
  @Test
  public void testHandleInfoRequests() throws Exception {
    S2A_INFO2_Packet packet = mock(S2A_INFO2_Packet.class);
    HashMap<String, Object> infoMap = new HashMap<String, Object>();
    infoMap.put("test", "test");
    when(packet.getInfo()).thenReturn(infoMap);
    when(server.getReply()).thenReturn(packet);

    this.server.handleResponseForRequest(GameServer.REQUEST_INFO);

    assertEquals("test", this.server.serverInfo.get("test"));
    verify(this.server).sendRequest(any(A2S_INFO_Packet.class));
  }
예제 #23
0
  @Override
  public void destroy() {
    super.destroy();

    if (client != null) {
      client.close();
    }

    if (server != null) {
      server.close();
    }

    game.getFogOfWar().destroy();
  }
  @Test
  public void testHandlePlayerRequests() throws Exception {
    SteamPlayer player = mock(SteamPlayer.class);
    S2A_PLAYER_Packet packet = mock(S2A_PLAYER_Packet.class);
    HashMap<String, SteamPlayer> playerMap = new HashMap<String, SteamPlayer>();
    playerMap.put("test", player);
    when(packet.getPlayerHash()).thenReturn(playerMap);
    when(server.getReply()).thenReturn(packet);

    this.server.handleResponseForRequest(GameServer.REQUEST_PLAYER);

    // Asserting null because we do not populate our list of players
    // from S2A Player Packets at the moment because it seems like Rust game servers
    // do not implement the ability to return valid data from those packets
    // Instead player data is fully retrieved from the RCON status command, instead
    // of a mixture of that command plus the S2A Player Packet
    assertNull(this.server.playerHash);
    verify(this.server).sendRequest(any(A2S_PLAYER_Packet.class));
  }
  /** Keeps server running until there are no players for longer than the set timeout */
  public void run() {
    boolean keepRunning = true;

    while (keepRunning) {
      // check that game still has players
      if (getNumberOfPlayers() < 1) {
        Date initialTime = new Date();
        while (getNumberOfPlayers() < 1) {
          Date currentTime = new Date();
          Long timeDiff = currentTime.getTime() - initialTime.getTime();
          if (GAME_TIMEOUT < timeDiff) {
            keepRunning = false;
          }
        }
      } else {
        boolean playersReady;
        // check if players are ready for question
        do {
          playersReady = true;

          try {
            for (GameServerWorker player : players) {
              if (!player.getReadyForQuestion()) {
                playersReady = false;
              }
            }
          } catch (ConcurrentModificationException e) {
            playersReady = false;
          }

          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

        } while (!playersReady);
        handleNextQuestion();
      }
    }
    // remove this game from the server
    gameServer.removeGameInstance(portNumber);
  }
예제 #26
0
  /**
   * Holds the main loop that processes incoming requests by first identifying its type, then
   * interpret the following data in each determined request class. Queued up responses created from
   * each request class will be sent after the request is finished processing.
   *
   * <p>The loop exits whenever the isPlaying flag is set to false. One of these occurrences is
   * triggered by a timeout. A timeout occurs whenever no activity is picked up from the client such
   * as being disconnected.
   */
  @Override
  public void run() {
    long lastActivity = System.currentTimeMillis();
    short requestCode = -1;

    while (!isDone) {
      try {
        // Extract the size of the package from the data stream
        short requestLength = DataReader.readShort(dataInputStream);

        if (requestLength > 0) {
          lastActivity = System.currentTimeMillis();
          // Separate the remaining package from the data stream
          byte[] buffer = new byte[requestLength];
          inputStream.read(buffer, 0, requestLength);
          DataInputStream dataInput = new DataInputStream(new ByteArrayInputStream(buffer));
          // Extract the request code number
          requestCode = DataReader.readShort(dataInput);
          // Determine the type of request
          GameRequest request = GameRequestTable.get(requestCode);
          // If the request exists, process like following:
          if (request != null) {
            request.setGameClient(this);
            // Pass input stream to the request object
            request.setDataInputStream(dataInput);
            // Parse the input stream
            request.parse();
            // Interpret the data
            request.doBusiness();
            try {
              // Retrieve any responses created by the request object
              for (GameResponse response : request.getResponses()) {
                // Transform the response into bytes and pass it into the output stream
                send(response);
              }
            } catch (IOException ex) {
              Log.printf_e("Client %s connection lost", session_id);
              isDone = true;
            }
          }
        } else {
          // If there was no activity for the last moments, exit loop
          if ((System.currentTimeMillis() - lastActivity) / 1000 >= Constants.TIMEOUT_SECONDS) {
            isDone = true;
          }
        }
      } catch (Exception ex) {
        Log.printf_e("Request [%d] Error:", requestCode);
        Log.println_e(ex.getMessage());
        Log.println_e("---");
        ex.printStackTrace();
      }
    }

    if (player != null) {
      removePlayerData();
    }

    // Remove this GameClient from the server
    GameServer.getInstance().deletePlayerThreadOutOfActiveThreads(session_id);

    Log.printf("Client %s has ended", session_id);
  }
예제 #27
0
  @Test
  public void testIsCorrectPlayerInGameNoAuth() throws Exception {
    when(service.isAuthorized(anyString())).thenReturn(false);

    assertFalse(gameServer.isCorrectPlayerInGame("aa"));
  }
예제 #28
0
 public void updateKeyStates(int id, KeyStates keyStates) {
   server.updateKeyStates(id, keyStates);
 }
예제 #29
0
 @Test
 public void testJoinRoomNoPlayer() {
   when(service.getUserBySession(anyString())).thenReturn(null);
   Room room = gameServer.joinRoom("aa", "aa", "aa");
   assertNull(room);
 }
예제 #30
0
 public Observable<String[]> getServerStatus(GameServer server) {
   return gameService.getServerStatus(new Tuple(server.getIp(), server.getPort()));
 }