首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Java套接字多次写入和读取

Java套接字多次写入和读取
EN

Stack Overflow用户
提问于 2018-06-13 08:28:49
回答 1查看 248关注 0票数 0

我想写一个客户端,它可以通过TCP与Vowpal Wabbit通信。本质上,我需要通过端口26542向大众主机发送像a b | c d e这样的消息。大众回复一条类似0.400000 0.200000 0.200000 0.200000的消息(不确定消息是如何终止的)。

因此,我需要多次执行此操作--发送消息、接收消息、发送消息、接收消息等等。

我用Java编写了以下代码。

代码语言:javascript
复制
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;
        }
    }
}

我使用这个类的方法如下:

代码语言:javascript
复制
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");

使用上面的代码,只打印第一个"send“的响应。另外两个返回null响应。

我也尝试了只使用"send“代码:

代码语言:javascript
复制
    public void send(final String message) throws IOException {
        outputWriter.print(message+"\n"); // important to add a newline
        outputWriter.flush();
    }

结果是只发送了第一条消息(我有一种方法可以在服务器端验证/记录它从客户端接收到的内容)。

为什么只有第一个发送成功,而所有其他发送都失败(尽管没有引发异常)?我该如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-13 08:49:33

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50827570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档