[英]Java Socket - passing int through object stream?
I am working on Java streams, In server side I'm trying to send int through objectOutputStream and recieve it in client side. 我正在处理Java流,在服务器端,我试图通过objectOutputStream发送int并在客户端接收它。 However I am not receiving anything in client side.
但是我没有在客户端收到任何东西。
Here is the server side sending int 这是服务器端发送int
public static int PLAYER1 = 1;
new ObjectOutputStream(player1.getOutputStream()).writeInt(PLAYER1);
Here is the client side receiving that int: 这是接收该int的客户端:
fromServer = new ObjectInputStream(socket.getInputStream());
Here is the part where I test the recieved int: 这是我测试接收到的int的部分:
int player = fromServer.readInt();
if(player == PLAYER1){
System.out.println("yy working");
}else{
System.out.println("not working");
}
The problem is that neither I get an error nor system out.. I am using ObjectStreams and not DataStreams because of some reasons. 问题是我既没有收到错误也没有退出系统。由于某些原因,我使用的是ObjectStreams,而不是DataStreams。
Your code doesn't seem to survive the call int player = fromServer.readInt();
您的代码似乎无法幸免于
int player = fromServer.readInt();
. 。 I would debug the call in readInt() or before that to see where it jumps out.
我会在readInt()或之前调试该调用,以查看它跳出的位置。
Call close()
or flush()
on server side: 在服务器端调用
close()
或flush()
:
public static int PLAYER1 = 1;
ObjectOutputStream oos = new ObjectOutputStream(player1.getOutputStream());
oos.writeInt(PLAYER1);
oos.flush();
// OR
oos.close();
flush()
will send any data already written to the client. flush()
将发送任何已写入客户端的数据。 This will leave you the possibility to reuse oos
. 这将使您有可能重用
oos
。
If you don't need oos
anymore, call close()
. 如果您不再需要
oos
,请调用close()
。 Calling close()
will flush any data not already sent. 调用
close()
将刷新所有尚未发送的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.