数据输入流和读取UTF丢失了数据



我正在使用java并从服务器接收了一些json字符串。我收到了带有 readUTF 的 json 字符串,但丢失了一些数据。我没有收到每个 json 数据包的前两个字符。 另一个问题是接收的 json 字符串有延迟。例如,服务器发送了一个 json 字符串,客户端无法接收它,直到服务器和客户端发送的大约 50 个 json 字符串突然显示所有 json 字符串。 主要问题是什么?

public void run() {
System.out.println("hi from thread" + id);
try {
clientSocket = new Socket("192.168.1.22", id);
output = new PrintStream(clientSocket.getOutputStream());
input = new DataInputStream(clientSocket.getInputStream());
inputLine = new DataInputStream(new BufferedInputStream(System.in));
} 
catch( IOException e){
System.out.println(e);
}
String responseLine;
try{      
while(true){
output.println( id + " ");
System.out.println("sent:" + id + " ");
responseLine = input.readUTF();
System.out.println("received: " + responseLine);
}
}
catch (IOException e) {
System.out.println(e);
}
}

由于服务器以UTF格式发送数据,所以我无法使用缓冲阅读器接收它们

我以前遇到过这样的应用程序,主要原因是 DataInputStream 它期望输入采用某种格式,我认为服务器不符合这种格式,请尝试使用 BufferedReader 代替:

BufferedReader input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

然后,每当您希望读取数据时,只需使用

some_string_here = input.readLine();

请注意,这要求发送的每个数据值都以结束行字符""或"\r"结尾。

最新更新