1

我正在创建一个服务器和一个客户端。现在我可以从 向 发送消息ClientServerThread并且ServerThread能够得到消息。但是当ServerThread尝试回复时,Client没有得到响应,但消息已发送。似乎它正在等待响应,但永远无法收到它。

服务器线程:

public class ServerThread extends Thread {
   private Socket socket;
   private DataOutputStream outToClient;
   private BufferedReader inFromClient;

   public ServerThread(Socket socket) {
      try {
         System.out.println("Thread started");
         this.socket = socket;
         outToClient = new DataOutputStream(socket.getOutputStream());
         inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public void run() {
      System.out.println("Thread running");
      try {
         System.out.println("ServerThread: " + inFromClient.readLine());
         outToClient.writeBytes("I Can help you");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

服务器:

public class Server {
   public static final int PORT = 5589;

   public static void main(String[] args) {
      ServerSocket socket;

      try {
         socket = new ServerSocket(5589);

         while (true)
            new ServerThread(socket.accept()).start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

客户:

public class Client {
   public static void main(String args[]) throws Exception {
      Socket socket = new Socket("localhost", App.PORT);
      BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      PrintWriter outToServer = new PrintWriter(socket.getOutputStream(), true);

      outToServer.println("Hello, I'm Lost");

      System.out.println(inFromServer.readLine()); //Hangs on this line

      socket.close();
   }
}
4

1 回答 1

3

您的数据在服务器端缓冲,并且在缓冲区已满之前不会自动发送:您应该.flush()在服务器端.writeBytes()确保它被发送,即使您没有达到缓冲区大小(这取决于操作系统和套接字配置)。

于 2012-12-25T00:22:09.830 回答