2014-03-01 24 views
3

前几天,我开始编写一个小多人游戏,在至极我用ObjectInputStreams和ObjectOutputStreams为了与服务器交换数据。但由于某种原因,服务器不会收到任何东西。所以我搜索了一些帮助,但是我发现的一切都是,我必须刷新ObjectOutputStream。当然,我做到了,但这不是解决我的问题的方法。所以我写了一个小测试应用程序,和我的游戏一样。但是仍然存在同样的问题:InputStream没有收到任何东西。因此,这里是我的测试程序代码:ObjectInputStream的不接工作

服务器应用程序:

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

+1

您告诉我们的是什么问题?你可以发布我们的任何堆栈跟踪或任何帮助 – Keerthivasan

+1

一个'阅读器'被用来读取文本,而不是二进制文件。不要使用那个 – fge

+1

你认为'while(in.available()<= 0){}'应该在服务器端做什么?你尝试删除它吗?提示:'in.readObject()'会一直等到有数据要读取,否则连接将会丢失。 – Pshemo

回答

0

刚刚尝试这一点,这是工作。

while(!line.equalsIgnoreCase("exit")){ 
    while(in.available() <= 0){ 
     line = in.readObject().toString(); 
     System.out.println(">>> recieved: " + line); 
    } 
} 

你误会了,在服务器代码你的第二个while循环括号。

+0

恩,谢谢,它工作,但我不明白。为什么流可以接收某些内容,但有零个或少于零个字节? 我认为应该有超过零字节可用,直到流可以接收的东西?! – Cydhra

+0

我不知道游戏的背景,所以,我怎么能回答?请描述你的游戏环境中创建新的问题。 – swapnil7

+0

@ user3368075告诉我,您的流正在接收“某事”,而有零或小于零字节可用。 – swapnil7