Search in sources :

Example 1 with Messengers

use of games.strategy.net.Messengers in project triplea by triplea-game.

the class LocalLauncher method launchInNewThread.

@Override
protected void launchInNewThread(final Component parent) {
    Exception exceptionLoadingGame = null;
    ServerGame game = null;
    try {
        gameData.doPreGameStartDataModifications(playerListing);
        final Messengers messengers = new Messengers(new HeadlessServerMessenger());
        final Set<IGamePlayer> gamePlayers = gameData.getGameLoader().createPlayers(playerListing.getLocalPlayerTypes());
        game = new ServerGame(gameData, gamePlayers, new HashMap<>(), messengers);
        game.setRandomSource(randomSource);
        // for debugging, we can use a scripted random source
        if (ScriptedRandomSource.useScriptedRandom()) {
            game.setRandomSource(new ScriptedRandomSource());
        }
        gameData.getGameLoader().startGame(game, gamePlayers, headless);
    } catch (final MapNotFoundException e) {
        exceptionLoadingGame = e;
    } catch (final Exception ex) {
        ClientLogger.logQuietly("Failed to start game", ex);
        exceptionLoadingGame = ex;
    } finally {
        gameLoadingWindow.doneWait();
    }
    try {
        if (exceptionLoadingGame == null) {
            game.startGame();
        }
    } finally {
        // todo(kg), this does not occur on the swing thread, and this notifies setupPanel observers
        // having an oddball issue with the zip stream being closed while parsing to load default game. might be caused
        // by closing of stream while unloading map resources.
        Interruptibles.sleep(100);
        gameSelectorModel.loadDefaultGameNewThread();
        SwingUtilities.invokeLater(() -> JOptionPane.getFrameForComponent(parent).setVisible(true));
    }
}
Also used : IGamePlayer(games.strategy.engine.gamePlayer.IGamePlayer) Messengers(games.strategy.net.Messengers) ServerGame(games.strategy.engine.framework.ServerGame) HashMap(java.util.HashMap) HeadlessServerMessenger(games.strategy.net.HeadlessServerMessenger) ScriptedRandomSource(games.strategy.engine.random.ScriptedRandomSource)

Example 2 with Messengers

use of games.strategy.net.Messengers in project triplea by triplea-game.

the class ClientModel method startGameInNewThread.

private void startGameInNewThread(final byte[] gameData, final Map<String, INode> players, final boolean gameRunning) {
    final GameData data;
    try {
        // this normally takes a couple seconds, but can take
        // up to 60 seconds for a freaking huge game
        data = IoUtils.readFromMemory(gameData, GameDataManager::loadGame);
    } catch (final IOException ex) {
        ClientLogger.logQuietly("Failed to load game", ex);
        return;
    }
    objectStreamFactory.setData(data);
    final Map<String, String> playerMapping = playersToNodes.entrySet().stream().filter(e -> e.getValue().equals(messenger.getLocalNode().getName())).collect(Collectors.toMap(Map.Entry::getKey, e -> IGameLoader.CLIENT_PLAYER_TYPE));
    final Set<IGamePlayer> playerSet = data.getGameLoader().createPlayers(playerMapping);
    final Messengers messengers = new Messengers(messenger, remoteMessenger, channelMessenger);
    game = new ClientGame(data, playerSet, players, messengers);
    new Thread(() -> {
        SwingUtilities.invokeLater(() -> JOptionPane.getFrameForComponent(ui).setVisible(false));
        try {
            // game will be null if we loose the connection
            if (game != null) {
                try {
                    data.getGameLoader().startGame(game, playerSet, false);
                    data.testLocksOnRead();
                } catch (final Exception e) {
                    ClientLogger.logError("Failed to start Game", e);
                    game.shutDown();
                    messenger.shutDown();
                    gameLoadingWindow.doneWait();
                    // an ugly hack, we need a better
                    // way to get the main frame
                    GameRunner.clientLeftGame();
                }
            }
            if (!gameRunning) {
                ((IServerReady) remoteMessenger.getRemote(CLIENT_READY_CHANNEL)).clientReady();
            }
        } finally {
            gameLoadingWindow.doneWait();
        }
    }, "Client Game Launcher").start();
}
Also used : ClientGame(games.strategy.engine.framework.ClientGame) ClientMessenger(games.strategy.net.ClientMessenger) IGamePlayer(games.strategy.engine.gamePlayer.IGamePlayer) TRIPLEA_STARTED(games.strategy.engine.framework.CliProperties.TRIPLEA_STARTED) TRIPLEA_HOST(games.strategy.engine.framework.CliProperties.TRIPLEA_HOST) Map(java.util.Map) RemoteMessenger(games.strategy.engine.message.RemoteMessenger) SetMapClientAction(games.strategy.engine.framework.network.ui.SetMapClientAction) INode(games.strategy.net.INode) PlayerListing(games.strategy.engine.framework.message.PlayerListing) Collection(java.util.Collection) Set(java.util.Set) Logger(java.util.logging.Logger) GameRunner(games.strategy.engine.framework.GameRunner) Component(java.awt.Component) Collectors(java.util.stream.Collectors) TRIPLEA_PORT(games.strategy.engine.framework.CliProperties.TRIPLEA_PORT) IChatPanel(games.strategy.engine.chat.IChatPanel) UnifiedMessenger(games.strategy.engine.message.unifiedmessenger.UnifiedMessenger) IChannelMessenger(games.strategy.engine.message.IChannelMessenger) CountDownLatch(java.util.concurrent.CountDownLatch) GameData(games.strategy.engine.data.GameData) List(java.util.List) ChangeToAutosaveClientAction(games.strategy.engine.framework.network.ui.ChangeToAutosaveClientAction) EventThreadJOptionPane(games.strategy.util.EventThreadJOptionPane) TRIPLEA_NAME(games.strategy.engine.framework.CliProperties.TRIPLEA_NAME) WaitWindow(games.strategy.engine.framework.ui.background.WaitWindow) SwingAction(games.strategy.ui.SwingAction) Setter(lombok.Setter) Getter(lombok.Getter) ChangeGameOptionsClientAction(games.strategy.engine.framework.network.ui.ChangeGameOptionsClientAction) Messengers(games.strategy.net.Messengers) HashMap(java.util.HashMap) Action(javax.swing.Action) MacFinder(games.strategy.net.MacFinder) RemoteName(games.strategy.engine.message.RemoteName) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) IMessengerErrorListener(games.strategy.net.IMessengerErrorListener) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) SwingUtilities(javax.swing.SwingUtilities) ClientLogin(games.strategy.engine.framework.startup.login.ClientLogin) ClientOptions(games.strategy.engine.framework.startup.ui.ClientOptions) IMessenger(games.strategy.net.IMessenger) GameDataManager(games.strategy.engine.framework.GameDataManager) IoUtils(games.strategy.io.IoUtils) ClientSetting(games.strategy.triplea.settings.ClientSetting) Nonnull(javax.annotation.Nonnull) GetGameSaveClientAction(games.strategy.engine.framework.network.ui.GetGameSaveClientAction) ChangeGameToSaveGameClientAction(games.strategy.engine.framework.network.ui.ChangeGameToSaveGameClientAction) TRIPLEA_CLIENT(games.strategy.engine.framework.CliProperties.TRIPLEA_CLIENT) Interruptibles(games.strategy.util.Interruptibles) SaveGameFileChooser(games.strategy.engine.framework.ui.SaveGameFileChooser) IOException(java.io.IOException) Chat(games.strategy.engine.chat.Chat) JOptionPane(javax.swing.JOptionPane) IServerReady(games.strategy.engine.framework.startup.launcher.IServerReady) GameObjectStreamFactory(games.strategy.engine.framework.GameObjectStreamFactory) TimeUnit(java.util.concurrent.TimeUnit) ClientLogger(games.strategy.debug.ClientLogger) IRemoteMessenger(games.strategy.engine.message.IRemoteMessenger) ChannelMessenger(games.strategy.engine.message.ChannelMessenger) IGameLoader(games.strategy.engine.framework.IGameLoader) CouldNotLogInException(games.strategy.net.CouldNotLogInException) Preconditions(com.google.common.base.Preconditions) ChatPanel(games.strategy.engine.chat.ChatPanel) IClientMessenger(games.strategy.net.IClientMessenger) IGamePlayer(games.strategy.engine.gamePlayer.IGamePlayer) Messengers(games.strategy.net.Messengers) GameData(games.strategy.engine.data.GameData) IOException(java.io.IOException) ClientGame(games.strategy.engine.framework.ClientGame) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) IOException(java.io.IOException) CouldNotLogInException(games.strategy.net.CouldNotLogInException)

Example 3 with Messengers

use of games.strategy.net.Messengers in project triplea by triplea-game.

the class StatusTest method testStatus.

@Test
public void testStatus() throws Exception {
    final IServerMessenger messenger = mock(IServerMessenger.class);
    final INode dummyNode = new Node("dummy", InetAddress.getLocalHost(), 0);
    when(messenger.getLocalNode()).thenReturn(dummyNode);
    when(messenger.getServerNode()).thenReturn(dummyNode);
    when(messenger.isConnected()).thenReturn(true);
    when(messenger.isServer()).thenReturn(true);
    final Messengers messengers = new Messengers(messenger);
    final StatusManager manager = new StatusManager(messengers);
    assertNull(manager.getStatus(messenger.getLocalNode()));
    manager.setStatus("test");
    Interruptibles.sleep(200);
    assertEquals("test", manager.getStatus(messenger.getLocalNode()));
    assertEquals("test", new StatusManager(messengers).getStatus(messenger.getLocalNode()));
}
Also used : INode(games.strategy.net.INode) Messengers(games.strategy.net.Messengers) INode(games.strategy.net.INode) Node(games.strategy.net.Node) IServerMessenger(games.strategy.net.IServerMessenger) Test(org.junit.jupiter.api.Test)

Example 4 with Messengers

use of games.strategy.net.Messengers in project triplea by triplea-game.

the class ServerLauncher method launchInNewThread.

@Override
protected void launchInNewThread(final Component parent) {
    try {
        // the order of this stuff does matter
        serverModel.setServerLauncher(this);
        serverReady = new ServerReady(clientCount);
        if (inGameLobbyWatcher != null) {
            inGameLobbyWatcher.setGameStatus(GameDescription.GameStatus.LAUNCHING, null);
        }
        serverModel.allowRemoveConnections();
        ui = parent;
        if (headless) {
            HeadlessGameServer.log("Game Status: Launching");
        }
        remoteMessenger.registerRemote(serverReady, ClientModel.CLIENT_READY_CHANNEL);
        gameData.doPreGameStartDataModifications(playerListing);
        abortLaunch = testShouldWeAbort();
        final byte[] gameDataAsBytes = gameData.toBytes();
        final Set<IGamePlayer> localPlayerSet = gameData.getGameLoader().createPlayers(playerListing.getLocalPlayerTypes());
        final Messengers messengers = new Messengers(messenger, remoteMessenger, channelMessenger);
        serverGame = new ServerGame(gameData, localPlayerSet, remotePlayers, messengers);
        serverGame.setInGameLobbyWatcher(inGameLobbyWatcher);
        if (headless) {
            HeadlessGameServer.setServerGame(serverGame);
        }
        // tell the clients to start,
        // later we will wait for them to all
        // signal that they are ready.
        ((IClientChannel) channelMessenger.getChannelBroadcastor(IClientChannel.CHANNEL_NAME)).doneSelectingPlayers(gameDataAsBytes, serverGame.getPlayerManager().getPlayerMapping());
        final boolean useSecureRandomSource = !remotePlayers.isEmpty();
        if (useSecureRandomSource) {
            // server game.
            // try to find an opponent to be the other side of the crypto random source.
            final PlayerID remotePlayer = serverGame.getPlayerManager().getRemoteOpponent(messenger.getLocalNode(), gameData);
            final CryptoRandomSource randomSource = new CryptoRandomSource(remotePlayer, serverGame);
            serverGame.setRandomSource(randomSource);
        }
        try {
            gameData.getGameLoader().startGame(serverGame, localPlayerSet, headless);
        } catch (final Exception e) {
            ClientLogger.logError("Failed to launch", e);
            abortLaunch = true;
            if (gameLoadingWindow != null) {
                gameLoadingWindow.doneWait();
            }
        }
        if (headless) {
            HeadlessGameServer.log("Game Successfully Loaded. " + (abortLaunch ? "Aborting Launch." : "Starting Game."));
        }
        if (abortLaunch) {
            serverReady.countDownAll();
        }
        if (!serverReady.await(ClientSetting.SERVER_START_GAME_SYNC_WAIT_TIME.intValue(), TimeUnit.SECONDS)) {
            System.out.println("Waiting for clients to be ready timed out!");
            abortLaunch = true;
        }
        remoteMessenger.unregisterRemote(ClientModel.CLIENT_READY_CHANNEL);
        new Thread(() -> {
            try {
                isLaunching = false;
                abortLaunch = testShouldWeAbort();
                if (!abortLaunch) {
                    if (useSecureRandomSource) {
                        warmUpCryptoRandomSource();
                    }
                    if (gameLoadingWindow != null) {
                        gameLoadingWindow.doneWait();
                    }
                    if (headless) {
                        HeadlessGameServer.log("Starting Game Delegates.");
                    }
                    serverGame.startGame();
                } else {
                    stopGame();
                    if (!headless) {
                        SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(ui, "Problem during startup, game aborted."));
                    } else {
                        System.out.println("Problem during startup, game aborted.");
                    }
                }
            } catch (final MessengerException me) {
                // if just connection lost, no need to scare the user with some giant stack trace
                if (me instanceof ConnectionLostException) {
                    System.out.println("Game Player disconnection: " + me.getMessage());
                } else {
                    me.printStackTrace(System.out);
                }
                // wait for the connection handler to notice, and shut us down
                try {
                    // we are already aborting the launch
                    if (!abortLaunch) {
                        if (!errorLatch.await(ClientSetting.SERVER_OBSERVER_JOIN_WAIT_TIME.intValue(), TimeUnit.SECONDS)) {
                            System.err.println("Waiting on error latch timed out!");
                        }
                    }
                } catch (final InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                stopGame();
            } catch (final Exception e) {
                e.printStackTrace(System.err);
                if (headless) {
                    System.out.println(DebugUtils.getThreadDumps());
                    HeadlessGameServer.sendChat("If this is a repeatable issue or error, please make a copy of this savegame " + "and contact a Mod and/or file a bug report.");
                }
                stopGame();
            }
            // having an oddball issue with the zip stream being closed while parsing to load default game. might be
            // caused by closing of stream while unloading map resources.
            Interruptibles.sleep(200);
            // either game ended, or aborted, or a player left or disconnected
            if (headless) {
                try {
                    System.out.println("Game ended, going back to waiting.");
                    // if we do not do this, we can get into an infinite loop of launching a game,
                    // then crashing out, then launching, etc.
                    serverModel.setAllPlayersToNullNodes();
                    final File f1 = new File(ClientSetting.SAVE_GAMES_FOLDER_PATH.value(), SaveGameFileChooser.getAutoSaveFileName());
                    if (f1.exists()) {
                        gameSelectorModel.load(f1, null);
                    } else {
                        gameSelectorModel.resetGameDataToNull();
                    }
                } catch (final Exception e1) {
                    ClientLogger.logQuietly("Failed to load game", e1);
                    gameSelectorModel.resetGameDataToNull();
                }
            } else {
                gameSelectorModel.loadDefaultGameNewThread();
            }
            if (parent != null) {
                SwingUtilities.invokeLater(() -> JOptionPane.getFrameForComponent(parent).setVisible(true));
            }
            serverModel.setServerLauncher(null);
            serverModel.newGame();
            if (inGameLobbyWatcher != null) {
                inGameLobbyWatcher.setGameStatus(GameDescription.GameStatus.WAITING_FOR_PLAYERS, null);
            }
            if (headless) {
                // tell headless server to wait for new connections:
                HeadlessGameServer.waitForUsersHeadlessInstance();
                HeadlessGameServer.log("Game Status: Waiting For Players");
            }
        }, "Triplea, start server game").start();
    } finally {
        if (gameLoadingWindow != null) {
            gameLoadingWindow.doneWait();
        }
        if (inGameLobbyWatcher != null) {
            inGameLobbyWatcher.setGameStatus(GameDescription.GameStatus.IN_PROGRESS, serverGame);
        }
        if (headless) {
            HeadlessGameServer.log("Game Status: In Progress");
        }
    }
}
Also used : IGamePlayer(games.strategy.engine.gamePlayer.IGamePlayer) PlayerID(games.strategy.engine.data.PlayerID) ConnectionLostException(games.strategy.engine.message.ConnectionLostException) Messengers(games.strategy.net.Messengers) ServerGame(games.strategy.engine.framework.ServerGame) MessengerException(games.strategy.engine.message.MessengerException) MessengerException(games.strategy.engine.message.MessengerException) ConnectionLostException(games.strategy.engine.message.ConnectionLostException) CryptoRandomSource(games.strategy.engine.random.CryptoRandomSource) IClientChannel(games.strategy.engine.framework.startup.mc.IClientChannel) File(java.io.File)

Aggregations

Messengers (games.strategy.net.Messengers)4 IGamePlayer (games.strategy.engine.gamePlayer.IGamePlayer)3 ServerGame (games.strategy.engine.framework.ServerGame)2 HashMap (java.util.HashMap)2 Preconditions (com.google.common.base.Preconditions)1 ClientLogger (games.strategy.debug.ClientLogger)1 Chat (games.strategy.engine.chat.Chat)1 ChatPanel (games.strategy.engine.chat.ChatPanel)1 IChatPanel (games.strategy.engine.chat.IChatPanel)1 GameData (games.strategy.engine.data.GameData)1 PlayerID (games.strategy.engine.data.PlayerID)1 TRIPLEA_CLIENT (games.strategy.engine.framework.CliProperties.TRIPLEA_CLIENT)1 TRIPLEA_HOST (games.strategy.engine.framework.CliProperties.TRIPLEA_HOST)1 TRIPLEA_NAME (games.strategy.engine.framework.CliProperties.TRIPLEA_NAME)1 TRIPLEA_PORT (games.strategy.engine.framework.CliProperties.TRIPLEA_PORT)1 TRIPLEA_STARTED (games.strategy.engine.framework.CliProperties.TRIPLEA_STARTED)1 ClientGame (games.strategy.engine.framework.ClientGame)1 GameDataManager (games.strategy.engine.framework.GameDataManager)1 GameObjectStreamFactory (games.strategy.engine.framework.GameObjectStreamFactory)1 GameRunner (games.strategy.engine.framework.GameRunner)1