有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从socket python服务器接收消息

我试图用bufferreader读取socket上的消息

我的客户:

Socket socket = new Socket("10.0.0.4", 12345);

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

System.out.println(in.readLine());

我的python服务器:

(client, (address, _)) = server.accept()  # Accept to new clients (Accept to new command from the phone)
client.send("Hello from server")

但是,当我从服务器向客户机发送消息时,代码在最后一行System.out.println(in.readLine());中得到堆栈,就像他在等待什么一样

当我关闭服务器时,我得到一个错误

如何使用Java从服务器读取输入


共 (1) 个答案

  1. # 1 楼答案

    正如@James comment所述,您似乎正在等待服务器未发送的回车或换行(完整行)

    这会导致您的代码一直等待,直到收到\n\r\r\n为止

    readLine()

    Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

    所以你的^{cd4>}从不考虑终止该行,而是让它一直等待结束。为了避免这种情况,请不要发送:

       client.send("Hello from server")
    

    发送

       client.send("Hello from server\n")
    

    或者更好的是,检查Python库是否有类似于sendLine()方法的东西


    为了循环接收服务器的消息,类似的方法可能会起作用:

    while (socket.isConnected()) 
    {
      String inputLine;
      while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
    }