2012-02-25 151 views
1

我正在做简单的Java客户端服务器。这是我的客户代码。inputStream数据丢失

try { 
     socket = new Socket(serverIP, serverport); 
     dataStream = new DataOutputStream(new BufferedOutputStream(
       socket.getOutputStream())); 
     long[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 
     for (int i = 0; i < data.length; i++) { 
      dataStream.writeLong(data[i]); 
      System.out.println("So far" + dataStream.size()); 
     } 
    } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (socket != null) 
      try { 
       dataStream.flush(); 
       socket.close(); 
       dataStream.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
    } 

这可以正常工作,因为我可以看到一堆字节已经写入服务器。这里是服务器代码。

try { 
      ServerSocket newSocket = new ServerSocket(2503); 
      while (true) { 
       connectionSocket = newSocket.accept(); 
       input = new DataInputStream(new BufferedInputStream(connectionSocket.getInputStream()));     
       System.out.println(input.readLong()); 
      } 

然而,没有数据被成功地从服务器套接字读出,connectionSocket.getInputStream.available()返回0字节。让我们假设每个变量都被正确地声明。任何想法为什么?感谢帮助。

+0

尝试添加环; (int i = 0; i <9; i ++)System.out.println(input.readLong());' – 2012-02-25 04:21:40

回答

0

抽水马桶/关闭流之前关闭套接字。

[当时:冲洗/关闭流,代码被更新之前]

+0

其实我做到了,我会修改我的代码以使其更清晰。谢谢 – 2012-02-25 04:41:42

+0

已更新的答案。 – 2012-02-25 04:56:23

+0

原来我没有在关闭它之前冲洗插座。现在我懂了。谢谢你,顺便说一下,我认为DataOutputStream在写入之后会自动刷新,它不会:( – 2012-02-25 14:44:09

0

您的循环在每次传递时都会调用accept,这会阻塞,直到下一个客户端连接。因此,第一个客户端附加,它读取一个长,打印,然后循环阻塞等待另一个连接附加。你需要在循环之外移动它。可能在一个单独的线程中,因为如果您在同一个线程上迭代流,则新客户端无法连接,直到它完成第一个客户端。这是下一步,但这里是你如何解决您的问题:

try { 
    ServerSocket newSocket = new ServerSocket(2503); 
    while(!done) { 
     Socket nextClient = newSocket.accept(); 
     // it's better to start a thread and put the call to this method in there 
     // so the thread owning the ServerSocket can loop back around and accept 
     // another client should another connect while it's servicing this client 
     handleNewClient(nextClient); 
    } 
} finally { 
    newSocket.close(); 
} 

public void handleNewClient(Socket client) { 
    boolean done = false; 
    DataInputStream in = new DataInputStream(new BufferedInputStream(client.getInputStream())); 
    while(!done) { 
     try { 
     Long l = in.readLong(); 
     System.out.println(l); 
     } catch(EOFException e) { 
     // this is not a great way to end the conversation from a client. 
     // better to either know how much you can read the stream (ie count of bytes), 
     // or use a termination encoding. Otherwise you have to wait till the client 
     // closes their side which throws EOFException. 
     done = true; 
     } 
    }  
} 
+1

方法** public void nextClient(Socket client)**应该是** public void handleNewclient(套接字客户端)**?谢谢 – 2012-02-25 04:46:03

+0

是的,我修正了这个问题。 – chubbsondubs 2012-02-25 05:26:24