来自socket的DataInputStream

时间:2012-02-29 05:46:49

标签: java stream io

更新 - 转到一致类型提供的解决方案

客户端向服务器套接字发送消息,然后服务器使用原始消息响应客户端。在引入后一种功能时,服务器只接收一条消息而不是继续接收所述消息,并且不响应客户端。评论添加的行。任何关于挂断的见解都会很棒。

客户端,发布评论和响应代码更新:

{  private Socket socket              = null;
   private BufferedReader  console   = null;
   private DataInputStream  streamIn   = null;
   private DataOutputStream streamOut = null;

  while (!line.equals(".bye"))
  {  try
     {  line = console.readLine();
        streamOut.writeUTF(line); //Send console data to server socket
        String reply = streamIn.readUTF(); //Recieve confirmation msg from server
        System.out.println( reply ); //Print the msg
        streamOut.flush();
     }

   public void start() throws IOException
   {  console = new BufferedReader(new InputStreamReader(System.in)); //Changed console to BufferedReader
      streamIn  = new DataInputStream(socket.getInputStream());
      streamOut = new DataOutputStream(socket.getOutputStream());
   }
   public void stop()
   {  try
      {  if (console   != null)  console.close();
         if (streamOut != null)  streamOut.close();
         if (streamIn != null)  streamIn.close(); //Is it good practice to close
         if (socket    != null)  socket.close();
      }

服务器端,已发布评论。

   public void handleClient() throws IOException {
      boolean done = false;
      try {
      System.out.println("Server Thread " + ID + " running.");
      while (!done) {
        String nextCommand = streamIn.readUTF();
        if( nextCommand.equals(".bye") ) {
           System.out.println("Client disconnected with bye.");
           done = true;
        } else {
           System.out.println( nextCommand );
           String nextReply = "\"You sent me ->" +nextCommand.toUpperCase() + "\"\n";
           streamOut.writeUTF( nextReply );
        }
     }
   } finally {
     streamIn.close();
     streamOut.close();
     socket.close();
   }
   }
   public void open() throws IOException
   {
      streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
      streamOut = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
//      streamOut = new DataOutputStream(socket.getOutputStream());
  }
   public void close() throws IOException
   {  if (socket != null)    socket.close();
      if (streamIn != null)  streamIn.close();
      if (streamOut != null) streamOut.close();
   }

1 个答案:

答案 0 :(得分:1)

你正在使用writeUTF和readUTF但在一个地方streamIn.readLine()我期望在等待新行时阻止它。我怀疑你需要一致地使用readUTF。

BTW控制台不是数据流,它的文本和我建议你使用BufferedReader。