Java:套接字未获取输入

标签 java sockets input io output

所以,我正在制作一个井字游戏项目,我遇到了网络部分的问题,一切都完成了,只缺少连接玩家彼此的部分,这是有问题的类:

public class Enemy implements Runnable{
    private static Socket enemy;

    public Enemy(Socket sock){
        enemy = sock;
    }

    public static void passaJogada(int xPos, int yPos){
        try {
            PrintWriter saida = new PrintWriter(enemy.getOutputStream());
            String x = "" + xPos;
            saida.println(x);
            String y = "" + yPos;
            System.out.print(x + y);
            saida.println(y);

        } catch (IOException e) {
            System.out.println("Ocorreu um erro!");
        }    
    }

    public void run() {
        try {
            BufferedReader entrada = new BufferedReader(new InputStreamReader(enemy.getInputStream()));
            while(!EndGameWindow.getEnd()) {    
                int x = Integer.parseInt(entrada.readLine());
                int y = Integer.parseInt(entrada.readLine());
                GameWindow.gameButton[x][y].fazerJogada(x,y);
            }
            entrada.close();
        } catch (IOException e) {
            System.out.println("Um errro ocorreu!");
        }
    }
}

我不知道发生了什么,我只知道 PrintWriter 正在写入,但 BufferedReader 没有读取。

只需忽略变量和方法的葡萄牙语名称。

最佳答案

请参阅 PrintWriter 的 API ,特别是您正在使用的单参数 OutputStream 构造函数:

Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream.

换句话说,PrintWriter 已被缓冲并且需要刷新。要启用自动行刷新,请使用适当的构造函数

PrintWriter saida = new PrintWriter(enemy.getOutputStream(), true);

...或显式刷新 PrintWriter:

....
saida.println(y);
saida.flush();

关于Java:套接字未获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019094/

相关文章:

python - 什么 SendMessage 用于将键直接发送到另一个窗口?

java - 我如何从中创建一棵树?

c - 为什么我收到的字节数比我发送的字节数多?

c++ - TCP IOCP 在 acceptex 之后收不到

java - 如何创建具有两个字段的自定义类的列表并获取输出?

python - 递归,使用输入调用函数

java - 从 eclipse 导出后重命名 war 文件以命中 Web api

java - Spring Integration 通过 tcp 连接接收和发送消息

java - 无法访问 ValueChangeListener 之外的 UIComponent 值

php - 什么是套接字 (MySQL)