我的套接字API中的读取功能不起作用,并滞后

问题描述 投票:0回答:1

据我所知,我制作了一种单模式国际象棋游戏,没有任何错误,因此我开始了多人游戏模式。成功连接两个播放器后,一个窗口(服务器播放器窗口)可以工作,但对手窗口滞后于特定行"movement = opponentPlayer.in.readLine();",它没有显示任何错误或任何内容,实际上,它停止了窗口的响应而未显示任何进度如图here

代码:

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);
    }

系统消息:

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

Process finished with exit code -1
java serversocket
1个回答
0
投票

输入流中的read方法是一个阻塞调用(如解释的in the api)。因此,程序到达readLine()方法后,将始终等待输入。如果从gui调用此方法,它将停止gui并冻结。

一种解决方案是在另一个thread中执行您的代码,以免主线程被阻塞。在线程中接收到数据之后,您可以通知gui或任何其他类有新的动作(或任何其他数据)可用。

© www.soinside.com 2019 - 2024. All rights reserved.