Java通过Socket发送和接收多条消息

时间:2017-10-19 11:03:13

标签: java sockets

我们需要实现一个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

有什么不对吗?

1 个答案:

答案 0 :(得分:1)

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

如果流在到达行结束之前终止,则readLine()将返回null,如' \ n'或者' \ r'。

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

尝试添加' \ n'在你的消息结束时。

希望这会有所帮助。

相关问题