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