我开始使用Java和套接字,而且我在使用 DataInputStream 时遇到了一些问题。 我收到的电报中包含消息本身前4个字节的消息长度,因此在第一次迭代中我只读取了这个内存部分。 当我再次读取传入的消息时,我注意到前4个字节消失了,所以我需要在我创建的方法中减去这4个字节来计算消息长度本身。 问题是:输入数据的缓冲区是否丢失了我已读过的字节数?我在Java文档中找不到任何内容,但由于我的经验不足,我可能会遗漏一些东西。
这是数据读取的方法:
/**
* 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;
答案 0 :(得分:2)
输入数据的缓冲区是否会丢失我已经读过的字节
是的,当然可以。 TCP呈现字节流。你消耗了它的一部分,它消失了。与阅读文件没有什么不同。
您应该使用DataInputStream.readInt()
来读取长度字,如果它是二进制的,然后DataInputStream.readFully()
来读取数据。