inputStream数据丢失

时间:2012-02-25 04:15:00

标签: java tcp

我在Java中使用简单的客户端服务器。这是我的客户端代码。

 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个字节。让我们假设每个变量都被正确地声明了。知道为什么吗?感谢帮助。

2 个答案:

答案 0 :(得分: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 :(得分:0)

在关闭套接字之前刷新/关闭流

[是:在代码更新之前刷新/关闭流]