Java 每次我读取一段传入消息时,套接字是否都会清理部分缓冲区?
我已经开始使用Java和sockets,但DataInputStream出现了一些问题。 我收到一封电报,其中包含消息本身前4个字节中的消息长度,所以在第一次迭代中,我只读取这个内存部分。 当我再次阅读传入的消息时,我注意到前4个字节已经消失,所以我需要在我创建的计算消息长度的方法中减去这4个字节。 问题是:传入数据的缓冲区是否丢失了我已经读取的字节?我在Java文档中找不到任何东西,但我可能因为缺乏经验而遗漏了一些东西 这是数据读取的方法:Java 每次我读取一段传入消息时,套接字是否都会清理部分缓冲区?,java,sockets,buffer,datainputstream,Java,Sockets,Buffer,Datainputstream,我已经开始使用Java和sockets,但DataInputStream出现了一些问题。 我收到一封电报,其中包含消息本身前4个字节中的消息长度,所以在第一次迭代中,我只读取这个内存部分。 当我再次阅读传入的消息时,我注意到前4个字节已经消失,所以我需要在我创建的计算消息长度的方法中减去这4个字节。 问题是:传入数据的缓冲区是否丢失了我已经读取的字节?我在Java文档中找不到任何东西,但我可能因为缺乏经验而遗漏了一些东西 这是数据读取的方法: /** * It receives data fr
/**
* It receives data from a socket.
*
* @param socket The communication socket.
* @param lengthArea The area of the header containing the length of the message to be received.
* @return The received data as a string.
*/
static String receiveData(Socket socket, int lengthArea) {
byte[] receivedData = new byte[lengthArea];
try {
DataInputStream dataStream = new DataInputStream(socket.getInputStream());
int bufferReturn = dataStream.read(receivedData, 0, lengthArea);
System.out.println("Read Data: " + bufferReturn);
} catch (IOException e) {
// Let's fill the byte array with '-1' for debug purpose.
Arrays.fill(receivedData, (byte) -1);
System.out.println("IO Exception.");
}
return new String(receivedData);
}
这是我用来计算消息长度的方法:
/**
* It converts the message length from number to string, decreasing the calculated length by the size of the message
* read in the header. The size is defined in 'Constants.java'.
*
* @param length The message size.
* @return The message size as an integer.
*/
static int calcLength(String length) {
int num;
try {
num = Integer.parseInt(length) + 1 - MESSAGE_LENGTH_AREA_FROM_HEADER;
} catch (Exception e) {
num = -1;
}
return num;
}
Constants.java
MESSAGE_LENGTH_AREA_FROM_HEADER = 4;
传入数据的缓冲区是否丢失了我已经读取的字节
是的,当然有。TCP呈现一个字节流。你吃了一部分,它就不见了。与从文件中读取没有区别
您应该使用
DataInputStream.readInt()
读取二进制长度单词,然后使用DataInputStream.readFully()
读取数据。Ok!非常感谢。我不能使用readInt(),因为传入的消息不是二进制的,但现在我完全理解了为什么需要减去这4个字节。