[英]Java send and receive multiple messages via 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”。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.