簡體   English   中英

Java套接字多次讀寫

[英]Java socket multiple writes and reads

我想編寫一個可以通過TCP與Vowpal Wabbit通信的客戶端。 本質上,我需要發送諸如ab | cde ab | cde通過端口26542到VW主機。VW響應消息為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();
    }

事實證明,僅發送了第一條消息(我可以在服務器端驗證/記錄從客戶端收到的消息)。

為什么只有第一個發送成功,而所有其他發送都失敗(盡管沒有引發異常)? 我該如何解決?

如果readLine()返回null,則對等方已關閉連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM