我正在尝试从第 3 方服务器接收 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'
?
谢谢
最佳答案
直接使用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.";
}
关于JAVA:TCP readline() 终止,二进制零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646436/