2017-06-03 64 views
0

客户端发送一条消息,然后服务器收到消息并回复消息。我不知道客户为什么不能阅读回应。如果我删除客户端中的读取部分,服务器可以获取消息。但对于下面的代码,没有任何工作。另外我尝试了flush(),它仍然不起作用。Java套接字可以让客户端无法读取数据

对于客户

public void run() { 

    try (Socket echoSocket = new Socket(HOSTNAME, Integer.parseInt(PORTNUMBER)); 
      DataOutputStream dOut = new DataOutputStream(echoSocket.getOutputStream()); 
      DataInputStream dIn = new DataInputStream(echoSocket.getInputStream()); 
    ) { 

     while (true) { 


      command = UI.commandQueue.take() 
      dOut.writeInt(Message.toByteArray(command).length); 
      dOut.write(Message.toByteArray(command)); 


      int length; 
      while((length = dIn.readInt()) != 0) { 
      if (length > 0){ 
       byte[] messagebyte = new byte[length]; 
       dIn.readFully(messagebyte, 0, messagebyte.length); 
       try { 
        msg = Message.fromByteArray(messagebyte); 
        testDisplay(msg); 
       } catch (Exception e1) { 
        // TODO Auto-generated catch block 
        e1.printStackTrace(); 
       } 
       testDisplay(msg); 
      } 
      } 


     } 

    }catch (UnknownHostException e) { 
     UI.display("Don't know about host " + HOSTNAME); 
    } catch (IOException e) { 
     UI.display("Couldn't get I/O for the connection to " + HOSTNAME); 
    } 
} 

对于服务器

public void run() { 

    try (ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PORT_NUMBER)); 
      Socket clientSocket = serverSocket.accept(); 

      DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream()); 
      DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());) { 
     int length; 
     while ((length = dIn.readInt()) != 0) { 
      if (length > 0) { 
       byte[] messagebyte = new byte[length]; 
       dIn.readFully(messagebyte, 0, messagebyte.length); // read the 
                   // message 
       Message msg; 
       try { 
        msg = Message.fromByteArray(messagebyte); 
        testDisplay(msg); 
        dOut.writeInt(Message.toByteArray(msg).length); 
        dOut.write(Message.toByteArray(msg)); 
        UI.display("ack sent"); 
       } catch (Exception e) { 
        // TODO Auto-generated catch block 
        UI.display(e.getMessage()); 
       } 

      } 
      } 
    } catch (IOException e) { 
     UI.display(
       "Exception caught when trying to listen on port " + PORT_NUMBER + " or listening for a connection"); 
     UI.display(e.getMessage()); 
    } 

} 
+0

你是否需要你的服务器来连续接收和发送来自多个客户端的数据?我可以在你的代码中看到很多错误,我有一个解决方案给你,但需要首先得到你的反馈。 –

回答

0

您的服务器呼应每个请求一个响应,但您的客户端试图读取每个请求多个响应,它永远不会,所以它阻止。

相关问题