NIO SocketChannelとIOソケットの間でオブジェクトをシリアル化しようとしています。私はNIO上でSerializable/writeObjectを使うことができないので、ByteArrayOutputStreamにオブジェクトを直列化し、配列の長さに続けて配列を送るコードを書くことを考えました。intをソケットとしてbyte []として送信してからintへ変換し直してください。
送信者機能が
public void writeObject(Object obj) throws IOException{
ByteArrayOutputStream serializedObj = new ByteArrayOutputStream();
ObjectOutputStream writer = new ObjectOutputStream(serializedObj);
writer.writeUnshared(obj);
ByteBuffer size = ByteBuffer.allocate(4).putInt(serializedObj.toByteArray().length);
this.getSocket().write(size);
this.getSocket().write(ByteBuffer.wrap(serializedObj.toByteArray()));
}
で、受信機は次のとおりです。
public Object readObject(){
try {
//Leggi dimensione totale pacchetto
byte[] dimension = new byte[4];
int byteRead = 0;
while(byteRead < 4) {
byteRead += this.getInputStream().read(dimension, byteRead, 4 - byteRead);
}
int size = ByteBuffer.wrap(dimension).getInt(); /* (*) */
System.out.println(size);
byte[] object = new byte[size];
while(size > 0){
size -= this.getInputStream().read(object);
}
InputStream in = new ByteArrayInputStream(object, 0, object.length);
ObjectInputStream ois = new ObjectInputStream(in);
Object res = ois.readUnshared();
ois.close();
return res;
} catch (IOException | ClassNotFoundException e) {
return null;
}
}
問題は、そのサイズ(*)ですいつも私のテストでは-1393754107 serializedObj.toByteArray()の長さに等しいです。私はキャスティングが正しく動作しない理由を理解していません。
キャスティング?どのようなキャスティングですか? – EJP