1

オブジェクトをクライアント (通常の IO) からサーバー (NIO) に転送しようとしています。オブジェクトが特定のサイズに達するまで送信は正常に機能し、サーバーは「無効な型コード」を示す「StreamCorruptException」をスローします。

サーバーで呼び出されるメソッドは次のとおりです。

  private void read(SelectionKey key) throws IOException, ClassNotFoundException {
    SocketChannel chan = (SocketChannel) key.channel();

    //read message object
    ByteBuffer buf = ByteBuffer.allocate(1024);
    ByteArrayOutputStream bos = new ByteArrayOutputStream(buf.capacity());
    int length = 0;
    int totalRead = 0;
    int read = chan.read(buf);
    System.out.println("read data " + read);
    if (read >= 4) {
      length = IoUtil.readInt(buf.array(), 0);
      bos.write(buf.array());
      buf.rewind();
      totalRead += read;
      LogUtil.log("length of data message is " + length);
    }
    while (totalRead < length) { //read until we get no more data
      read = chan.read(buf);
      if (read == -1) break;
      if (read == 0) continue;
      totalRead += read;
      System.out.println("I've read " + read + " bytes. Total amount of bytes " + totalRead);
      bos.write(buf.array());
      buf.rewind();
    }

    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray(), 4, length);
    ObjectInputStream inFromClient = new ObjectInputStream(bis);

    Message msg = (Message) inFromClient.readObject();

    SocketAddress sa = chan.socket().getRemoteSocketAddress();
    LogUtil.log(msg.getIdentifier() + "-Message von " + sa);


    commData.handleMessage(sa, msg);

  }

オブジェクトのサイズを先頭に追加して、NIO が適切に機能するようにします。ここで何が欠けていますか?

4

1 に答える 1