2017-11-29 16 views
-2

나는 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; 

답변

2

내가 답답했습니다 바이트를 수신 데이터의 버퍼 잃지 않는다 eady는 물론 그것을하지,

를 참조하십시오. TCP는 바이트 스트림을 제공합니다. 당신은 그것의 일부를 소비합니다, 그것은 사라졌습니다. 파일을 읽는 것과 다르지 않습니다.

길이가 2 진수이면 길이 단어를 읽으려면 DataInputStream.readInt()을 사용하고 데이터를 읽으려면 DataInputStream.readFully()을 사용해야합니다.

+0

좋아! 고맙습니다. 들어오는 메시지가 바이너리가 아니기 때문에 readInt()를 사용할 수 없지만, 이제 왜 4 바이트를 뺄 필요가 있는지 완전히 이해합니다. – Davide3i