Java ObjectInputStream不适用于套接字
几天前,我开始编写一个小型多人游戏,其中我使用ObjectInputStreams和ObjectOutputStreams与服务器交换数据。但是由于某种原因,服务器没有接收到任何东西。所以我搜索了一些帮助,但我发现的一切都是,我必须刷新ObjectOutputStream。我当然这样做了,但这不是解决我问题的办法。所以我写了一个小的测试应用程序,和我的游戏一样。但是仍然存在同样的问题:InputStream没有接收任何东西。下面是我的测试应用程序代码: 服务器应用程序:Java ObjectInputStream不适用于套接字,java,sockets,input,stream,Java,Sockets,Input,Stream,几天前,我开始编写一个小型多人游戏,其中我使用ObjectInputStreams和ObjectOutputStreams与服务器交换数据。但是由于某种原因,服务器没有接收到任何东西。所以我搜索了一些帮助,但我发现的一切都是,我必须刷新ObjectOutputStream。我当然这样做了,但这不是解决我问题的办法。所以我写了一个小的测试应用程序,和我的游戏一样。但是仍然存在同样的问题:InputStream没有接收任何东西。下面是我的测试应用程序代码: 服务器应用程序: try {
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(),但随后它就起作用了。
所以我希望,任何人都知道这个问题,能够帮助我
注:我既不是英国人也不是美国人,如果我的英语有错误,那么很抱歉试试这个,这个很管用
while(!line.equalsIgnoreCase("exit")){
while(in.available() <= 0){
line = in.readObject().toString();
System.out.println(">>> recieved: " + line);
}
}
while(!line.equalsIgnoreCase(“退出”)){
while(in.available())你已经告诉我们问题出在哪里了吗?你能给我们发一些stacktrace或任何帮助我们的东西吗阅读器
是用来阅读文本的,而不是二进制的。不要用它。while(in.available())你觉得怎么样嗯,谢谢,它工作了,但我不明白。为什么流可以接收一些东西,而有零或少于零字节可用???我认为应该有超过零字节可用,直到流可以接收一些东西?!我不知道游戏的上下文,所以我如何回答?请创建新的问题,描述你的game的上下文。@user3368075向我显示,当可用字节数为零或少于零字节时,流接收“某物”的位置。这里有一个新线程,主要问题是…应删除available()测试和循环。如果available()可用,读它基本上是无意义的