简体   繁体   English

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

[英]JAVA: TCP readline() termination, binary zero

I am trying to receive TCP data from a 3rd party server, whose messages are terminated with a binary zero ( '\\0' ) rather than newline ( '\\n ). 我正在尝试从第三方服务器接收TCP数据,该服务器的消息以二进制零( '\\0' )而不是换行符( '\\n )终止。 From what I understand, JAVA's readline() waits for an '\\n' termination, which might be the reason that my code hangs. 据我了解,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.";
    }

Is there a way to read a message from the server, such that '\\0' will denote the end of transmission rather than '\\n' ? 有没有办法从服务器读取消息,例如'\\0'表示传输结束而不是'\\n'

Thanks 谢谢

Just use directly the InputStreamReader : 只需直接使用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.";
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM