我们需要实现一个 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
有什么问题吗?
最佳答案
正如您在这里看到的:https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()
如果流在到达“\n”或“\r”等行尾提要之前终止,则 readLine() 将返回 null。
就像您的情况一样,您不发送 EOL,然后关闭流,从而返回 null。
尝试在消息末尾添加“\n”。
希望这有帮助。
关于Java通过Socket发送和接收多条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46828448/