Java套接字多次写入和读取

时间:2018-06-13 00:28:49

标签: java sockets tcp

我想编写一个可以通过TCP与Vowpal Wabbit通信的客户端。基本上,我需要通过端口26542向VW主机发送a b | c d e之类的消息。大众以0.400000 0.200000 0.200000 0.200000之类的消息进行响应(不确定消息是如何终止的)。

所以,我需要多次这样做 - 发送消息,接收消息,发送消息,接收消息等等。

我在Java中有以下代码。

public class MyClient {
    protected String host;
    protected int port;
    protected Socket socket;
    protected PrintWriter outputWriter;
    protected BufferedReader inputReader;

    public MyClient(String host, int port) throws IOException {
        socket = new Socket(host, port);
        outputWriter = new PrintWriter(socket.getOutputStream());
        inputReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public void send(final String message) throws IOException {
        outputWriter.print(message+"\n"); // important to add a newline
        outputWriter.flush();

        String responseStr = inputReader.readLine();
        System.out.println(responseStr);
        if (StringUtils.isBlank(responseStr)) {
            return;
        }
    }
}

我使用这个类如下:

MyClient client = new MyClient("host_ip", 26542); // the port used by VW
client.send("1:0.5:0.3 | feature11 feature21 feature31");
client.send("1:0.5:0.3 | feature12 feature22 feature32");
client.send("1:0.5:0.3 | feature13 feature23 feature33");

使用上面的代码,只有第一个"发送"的响应。打印出来。其他两个回复null

我也试过"发送"只有代码:

    public void send(final String message) throws IOException {
        outputWriter.print(message+"\n"); // important to add a newline
        outputWriter.flush();
    }

事实证明只发送了第一条消息(我有办法验证/登录服务器端从客户端收到的内容)。

为什么只有第一次发送成功但所有其他发送失败(虽然没有引发异常)?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

如果readLine()返回null,则对等体已关闭连接。