클라이언트가 바이트 배열 크기가 어떻게 다른지 알고 있습니까? 잘 알려진 방법 (서버 측에서도 이것을 관리해야합니다)은 다음 필드를 사용하여 패킷 내에 데이터를 캡슐화하는 것입니다. | TYPE | SIZE | DATA |
이렇게 클라이언트에 소켓 연결이 있고 DataInputStream (dataInputStream = new DataInputStream(socket.getInputStream())
)을 인스턴스화한다고 가정하면 위한
@Override
public void run() {
while(running) {
int pckType = readPacketType();
int pckSize = readPacketSize();
byte[] data = readPacketContent(pckSize);
// do something with data
// you can use Semaphore instances in order to maintains a set of permits if needed
}
}
private int readPacketType() {
int result = -1;
byte[] array = new byte[1];
try {
dataInputStream.read(array);
result = (int)array[0];
} catch (IOException ex) {
return -1;
}
return result;
}
private int readPacketSize() {
int result = -1;
byte[] array = new byte[4];
try {
dataInputStream.read(array);
result = ByteBuffer.wrap(array).getInt();
} catch (IOException ex) {
return -1;
}
return result;
}
private byte[] readPacketContent(int contentSize) {
byte[] result = new byte[contentSize];
try {
dataInputStream.read(result);
} catch (IOException ex) {}
return result;
}
내가 예를 들어, 할당 된 것을주의
의 TYPE 필드에 1 바이트, 4 바이트 : 클라이언트 run
방법이 같은 어떤 스레드의 데이터를 읽을 수있다 SIZE fi ELD
편집 : 당신은 LinkedBlockingQueue 등과 같은 인터페이스 BlockingQueue 인터페이스의 구현을 사용할 수 있습니다 . 다른 크기의 byte []를 넣고 일관되게 검색 할 수 있습니다 (순서와 크기 유지). 쉽게 확인하십시오;)
LinkedBlockingQueue<byte[]> lbq = new LinkedBlockingQueue<byte[]>();
String str1 = "blablabla";
String str2 = "blabla";
try {
lbq.put(str1.getBytes());
lbq.put(str2.getBytes());
lbq.put(str1.getBytes());
} catch (InterruptedException e) {
e.printStackTrace();
}
byte[] b = null;
int size = lbq.size();
for(int i=0; i<size; i++) {
try {
b = lbq.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(b.length);
}
제 문제를 올바르게 표현하지 못했습니다. 디코딩을 실제로 시작할 때까지받은 청크 (byte [])를 넣을 때 사용할 수있는 데이터 구조를 알아야합니다. 일단 디코딩을 시작하면, 그 청크 (바이트 [])를 선택하여 디코더로 보내고 싶습니다. 내가 BlockingQueue 사용할 수 있지만 큐에 읽기/쓰기 때 어떻게 바이트 [] 크기를 지정할 수 있습니까? – SohailAziz
미안 해요, 내가 어떻게이 문제를 오해하고 내가 BlockingQueue의 사용하는 경우 여전히 내가 BlockingQueue의 인스턴스를 사용하는 거라고 이후의 요구에 맞게 수 있는지 이해하고 하나의 객체 –
bardi
으로 바이트 [] (다른 크기의)로 공급하지 않습니다 나는 풋를 통해 (객체)와 테이크 (객체)의 바이트의 어떤 크기 [] 반환됩니다 다른 크기 바이트 [] 배열을 넣어? @bardi – SohailAziz