Java套接字-通过对象流传递int



我正在处理Java流,在服务器端,我试图通过objectOutputStream发送int,并在客户端接收它。然而,我在客户端没有收到任何东西。

这是服务器端发送int

public static int PLAYER1 = 1;
new ObjectOutputStream(player1.getOutputStream()).writeInt(PLAYER1);

这是客户端接收到的int:

fromServer = new ObjectInputStream(socket.getInputStream());

这是我测试收到的int的部分:

int player = fromServer.readInt();
if(player == PLAYER1){
System.out.println("yy working");
}else{
System.out.println("not working");
}

问题是我既没有得到错误,也没有得到系统。。由于某些原因,我使用的是ObjectStreams而不是DataStreams。

调用服务器端的close()flush()

public static int PLAYER1 = 1;
ObjectOutputStream oos = new ObjectOutputStream(player1.getOutputStream());
oos.writeInt(PLAYER1);
oos.flush();
// OR
oos.close();

flush()将向客户端发送已经写入的任何数据。这将使您有可能重复使用oos

如果您不再需要oos,请致电close()。调用close()将清除任何尚未发送的数据。

您的代码似乎无法通过调用int player = fromServer.readInt();。我会在readInt()或之前调试调用,看看它从哪里跳出来。

最新更新