【问题标题】:Java send and receive multiple messages via SocketJava 通过 Socket 发送和接收多条消息
【发布时间】:2018-03-31 09:44:53
【问题描述】:

我们需要实现一个 Socket 客户端,它应该连接到一个接受 TCP 连接的服务器。如果我通过 netcap 与服务器通信,我会立即得到它的响应(通过命令行)。

工作流程是:

nc 99.0.99.84 20000

然后我向服务器发送连接请求

*99*0##

我收到了 ACK 响应

*#*1##

我发送我的请求

*#18*802*86##

我收到回复

*#18*802*86*222241400##*#*1##

通过命令行,一切都很快。

所以我试图以这种方式使用 Socket 客户端来做到这一点

try {

            Socket socket = new Socket("99.0.99.84", 20000);

            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            System.out.println("Start");
            Thread.sleep(1000);
            String connectionRequest ="*99*0##";
            System.out.println("Sending connection request " + connectionRequest);
            out.println(connectionRequest);
            String connResponse = in.readLine();

            System.out.println("Response to connection is " + connResponse);
            Thread.sleep(500);
            String payload ="*#18*802*86##";
            System.out.println("Sending " + payload);
            out.println(payload);
            String response = in.readLine();


            System.out.println("Response is " + response);
            out.close();
            in.close();
            socket.close();

        } catch (UnknownHostException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

使用它时,客户端在很长一段时间内获取连接响应,然后以 response = null 退出

Sending connection request*99*0##
Response to connection is *#*1##*#*1##
Sending *#18*802*86##
Response is null

有什么问题吗?

【问题讨论】:

  • 响应是否以\r\n\r\n 结尾? readLine 会一直读到那个点,然后等到它得到它。
  • no...没有行尾元素...
  • 感谢您的评论,我使用 read() 通过读取每个字符的字符来解决

标签: java sockets


【解决方案1】:

如您所见:https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()

如果流在到达 '\n' 或 '\r' 之类的行尾提要之前终止,则 readLine() 将返回 null。

就像您的情况一样,您不发送 EOL 然后关闭流,从而返回 null。

尝试在您的消息末尾添加“\n”。

希望这会有所帮助。

【讨论】:

  • 谢谢,问题是我无法更改服务器发送消息的方式..
猜你喜欢
  • 1970-01-01
  • 2019-11-08
  • 2019-01-06
  • 2011-05-09
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多