【发布时间】:2014-04-02 13:33:34
【问题描述】:
几天前,我开始编写一个小型多人游戏,我使用 ObjectInputStreams 和 ObjectOutputStreams 来与服务器交换数据。但是由于某种原因,服务器没有收到任何东西。所以我寻求一些帮助,但我发现的一切都是,我必须刷新 ObjectOutputStream。我当然这样做了,但这不是我问题的解决方案。所以我写了一个小测试应用程序,它和我的游戏一样。但是仍然存在同样的问题: InputStream 没有收到任何东西。所以这是我的测试应用代码:
服务器应用程序:
try {
ServerSocket srvr = new ServerSocket(12975);
Socket client = srvr.accept();
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.flush();
System.out.println("server ready!");
String line = "";
while(!line.equalsIgnoreCase("exit")){
while(in.available() <= 0){}
line = in.readObject().toString();
System.out.println(">>> recieved: " + line);
}
client.close();
srvr.close();
System.exit(0);
} catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
System.exit(1);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
这是客户端应用程序:
try {
Socket client = new Socket("localhost", 12975);
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.flush();
ObjectInputStream in = new ObjectInputStream(client.getInputStream());
System.out.println("client ready!");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = "";
while(!line.equalsIgnoreCase("exit")){
System.out.print("> ");
line = input.readLine();
out.writeObject(line);
out.flush();
}
client.close();
System.exit(0);
} catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
我试图对双方都这样做:服务器->客户端和客户端->服务器,但是两个套接字都没有收到任何东西。任何研究都失败了,因为每个人似乎都在构造 OutputStream 后忘记了 flush(),但后来它起作用了。 所以我希望,任何人都知道这个问题并能够帮助我。
P.S:我既不是英国人也不是美国人,如果我的英语有错误,非常抱歉! :D
【问题讨论】:
-
您告诉我们有什么问题吗?您可以向我们发布任何堆栈跟踪或任何帮助
-
A
Reader用于读取文本,而不是二进制。不要使用那个 -
你认为
while (in.available() <= 0) {}应该在服务器端做什么?你试过删除它吗?提示:in.readObject()将等到有数据要读取,否则连接将丢失。