private void connectToTheServer() { this.connectionState = ConnectionState.CONNECTING_TO_THE_SERVER; while (running) { try { Gdx.app.debug(TAG, "Connecting to the server..."); socket = Gdx.net.newClientSocket(Net.Protocol.TCP, ip, port, socketHints); connectionState = ConnectionState.CONNECTED; Gdx.app.debug(TAG, "Connected to the server."); sendMessage( RTSProtocolManager.getInstance() .createNetworkMessageNewConnectionInfo( GameMain.getInstance().getPlayer().getName(), GameMain.getInstance().getPlayer().getNetworkId())); Gdx.app.debug(TAG, "Sending player information."); break; } catch (Exception e) { connectionState = ConnectionState.NOT_CONNECTED; Gdx.app.debug(TAG, "Could not connect to the server: " + e.getMessage()); Gdx.app.debug(TAG, "Trying again in a few seconds..."); try { Thread.sleep(1000); } catch (InterruptedException e1) { // Continue } } } }
private void listenNetworkMessagesUntilDisconnected() { if (socketType == SocketType.SERVER_SOCKET) { Gdx.app.debug(TAG, "Listening messages from the server."); } else if (socketType == SocketType.PLAYER_SOCKET) { Gdx.app.debug(TAG, "Listening messages from the player."); } InputStreamReader inputStream = new InputStreamReader(socket.getInputStream()); char[] readCharacter = new char[1]; // Read character will be stored in this array StringBuilder constructMessage = new StringBuilder(); while (running) { try { // Read one character from buffer or wait until there is a message in the buffer if (inputStream.read(readCharacter) == -1) { // Socket disconnected. running = false; } else { constructMessage.append(readCharacter[0]); // Message is too long? if (constructMessage.length() > NetworkManager.getInstance().NETWORK_MESSAGE_MAX_LENGTH_CHARACTERS) { constructMessage = new StringBuilder(); Gdx.app.debug(TAG, "WARNING: Network message was too long and was rejected!"); } if (readCharacter[0] == '>') { // End of the message reached, handle message if (socketType == SocketType.SERVER_SOCKET) { Gdx.app.debug(TAG, "Got message from the server: " + constructMessage); } else if (socketType == SocketType.PLAYER_SOCKET) { Gdx.app.debug( TAG, "Got message from the player " + player.getNumber() + ": " + constructMessage); } RTSProtocolManager.getInstance() .handleNetworkMessage(constructMessage.toString(), this); constructMessage = new StringBuilder(); } } } catch (Exception e) { Gdx.app.debug(TAG, "ERROR: while reading buffer: " + e.getMessage()); running = false; } } }