나는 Java 및 소켓 작업을 시작했습니다 내가 의 DataInputStream 몇 가지 문제가 있습니다. I는 I 단지이 메모리 부를 읽기 첫번째 반복에 있으므로, 메시지 자체의 처음 4 바이트의 메시지 길이를 포함하는 전문을 수신하고있다. 나는 다시 내가 처음 4 바이트가 사라진 것으로 나타났습니다 수신 메시지 읽을 때, 그래서 내가 메시지 길이 자체를 계산하기 위해 만든 방법에 그 4 바이트를 뺄 필요가있다. 질문 : 들어오는 데이터의 버퍼가 이미 읽은 바이트를 잃어 버리지 않습니까? 자바 문서에서 아무 것도 찾을 수 없지만 경험이 부족하여 뭔가를 놓친 것 같습니다. 들어오는 메시지의 세그먼트를 읽을 때마다 소켓이 버퍼의 일부를 정리합니까?
이
는 데이터 읽기의 방법 :/**
* 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;
좋아! 고맙습니다. 들어오는 메시지가 바이너리가 아니기 때문에 readInt()를 사용할 수 없지만, 이제 왜 4 바이트를 뺄 필요가 있는지 완전히 이해합니다. – Davide3i