【发布时间】: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() 通过读取每个字符的字符来解决