Search code examples
javaserversocket

the read function in my socket API does not work and lags


I made a single mode chess game that is has no bugs as far as i know and i started the multiplayer mode. After i connect the two players successfully, one window (the server player window) works but the opponent window lags the specific line "movement = opponentPlayer.in.readLine();", it shows no error or anything at all, in fact it stops the window from responding without showing any progress as shown here

Code:

private void receiveMovement() throws IOException {

        System.out.println("I Entered receiveMovement");
        String movement = null;
        if (serverPlayer != null) {
            System.out.println("I Entered serverPlayer");
            movement = serverPlayer.in.readLine();
            board.whiteTurn = movement.charAt(4) == 1;
        } else if (opponentPlayer != null) {
            System.out.println("I Entered opponentPlayer");
            movement = opponentPlayer.in.readLine();
            board.whiteTurn = movement.charAt(4) == 1;
        }
        System.out.println(movement);
//        int yAxis1 = movement.charAt(0) -'a';
//        int yAxis2 = movement.charAt(2) -'a';
//        System.out.println(yAxis1);
//        System.out.println(yAxis2);
//        Coordinate sourceCoordinate = new Coordinate(movement.charAt(1), yAxis1); //not sure of the order
//        Coordinate destinationCoordinate = new Coordinate(movement.charAt(3), yAxis2);
        assert movement != null;
        Coordinate sourceCoordinate = new Coordinate(movement.charAt(1), movement.charAt(0) - 'a');
        Coordinate destinationCoordinate = new Coordinate(movement.charAt(3), movement.charAt(2) - 'a');
        sourceTile = board.getTile(sourceCoordinate);
        destinationTile = board.getTile(destinationCoordinate);
    }

the system messages:

I Entered play Successfully
I Entered opponent play, i'm stuck
I Entered receiveMovement
I Entered opponentPlayer

Process finished with exit code -1

Solution

  • The read method in input streams is a blocking call (like explained in the api). Therefore your programm will always wait for input as soon as it reaches the readLine() method. If this method is called from a gui it will stop the gui and it freezes.

    A solution would be to execute your code in another thread so the main thread doesn't get blocked. After receiving the data in the thread you can inform the gui or any other class that there is a new move (or any other data) available.