Tomcat でメッセージを送受信するために、リモート サーバーへの SocketChannel を作成しました。リモート コンピューターからメッセージを受信するために、タスク専用のスレッドを使用しました (このスレッドのみがソケットから読み取ります)。
SocketChannel でいくつかのバイトが受信されると (新しいデータのために非ブロッキング モードで SocketChannel をポーリングし続けます)、最初に 4 バイトを読み取って次のメッセージの長さを取得し、次に SocketChannel から x バイトを割り当てて読み取ります。次に、デコードしてメッセージに再構築します。
以下は、受信スレッドのコードです。
@Override
public void run() {
while (true) { //Don't exit thread
//Attempt to read the size of the incoming message
ByteBuffer buf = ByteBuffer.allocate(4);
int bytesread = 0;
try {
while (buf.remaining() > 0) {
bytesread = schannel.read(buf);
if (bytesread == -1) { //Socket was terminated
}
if (quitthread) break;
}
} catch (IOException ex) {
}
if (buf.remaining() == 0) {
//Read the header
byte[] header = buf.array();
int msgsize = (0xFF & (int)header[0]) + ((0xFF & (int)header[1]) << 8)
+ ((0xFF & (int)header[2]) << 16) + ((0xFF & (int)header[3]) << 24);
//Read the message coming from the pipeline
buf = ByteBuffer.allocate(msgsize);
try {
while (buf.remaining() > 0) {
bytesread = schannel.read(buf);
if (bytesread == -1) { //Socket was terminated
}
if (quitthread) break;
}
} catch (IOException ex) {
}
parent.recvMessage(buf.array());
}
if (quitthread) {
break;
}
}
}
SocketChannel から受信した最初のバイトは問題なく、メッセージのデコードに成功しました。しかし、次に SocketChannel から読み取ると、ソケットが約 100 バイト先にスキップしたため、間違ったバイトが読み取られて長さとして解釈され、すべてが破損しました。
コードの何が問題になっていますか? SocketChannel から読み取っているスレッドは他にありません。