JAVA:TCP readline()终止,二进制零

时间:2015-02-21 13:37:58

标签: java tcp

我正在尝试从第三方服务器接收TCP数据,第三方服务器的消息以二进制零('\0')而不是换行符('\n)终止。根据我的理解,JAVA的readline()等待'\n'终止,这可能是我的代码挂起的原因。

try {
    socket = new Socket(hostip, portNum);
    BufferedReader inFromServer = new BufferedReader(new InputStreamReader (socket.getInputStream()));
    msg = inFromServer.readLine();
    socket.close();
    } catch (IOException e) {
        msg = "Connection failed. IOException.";
    }

有没有办法从服务器读取消息,以便'\0'表示传输结束而不是'\n'

由于

1 个答案:

答案 0 :(得分:2)

直接使用InputStreamReader

    try {
        socket = new Socket(hostip, portNum);
        InputStreamReader in = new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8);

        StringBuffer sb = new StringBuffer();
        int ch = 'a';

        while((ch = in.read()) != (char)0){
            if(ch == -1) break;
            System.out.println(ch);
            sb.append((char)ch);
        }

        msg = sb.toString();
        socket.close();
        } catch (IOException e) {
            msg = "Connection failed. IOException.";
        }