Serialize/Deserialize using Streams
Posted on 2007-10-01
I am using following streams to send objects on NIO sockets:
For sending data( Few code snippet):==>
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutputStream oStream = new ObjectOutputStream( bStream );
// serializedata is a object to be sent on socketchannel
byteArray = bStream.toByteArray();
// objOutput is ByteBuffer
numWrite = sc.write(objOutput);
// Some extra logic to stop sender
For receiving data ( Few code snippet):==>
numRead = sc.read(objInput );
byteArray = objInput.array();
ByteArrayInputStream bStream1 = new ByteArrayInputStream(byteArray, offset,limit - offset);
ObjectInputStream iStream = new ObjectInputStream( bStream1 );
serializeData = (SerializedData) iStream.readObject();
My program is working fine the only problem is that it is taking more time than old IO.
I want to use global Stream objects (rather than creating a new object for each message as used in code snippet above).
When i am trying to use global objects .. getting StreamCorruptedException.
Can anyone help me and let me know the reason for this exception and also the way to use global stream objects to speedup.?
Any other way to improve performance will be of great help.
Thanks in advance.