Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

what is th use of ByteBuffers ?  RSS feed

 
merwin pinto
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Is it possible to set java-objects to ByteBuffers ?
can we write an object into a byte buffer? or read an object fron a ByteBuffer.
suppose i have to send an object .. MyObject into a ByteBuffer...how can i do it?

i am trying to send objects thru the SocketChannel... which can read only into a bytebuffer
Please help me with this
 
Manuel Moons
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take a look at the ObjectOutputStream class



I think this is what you need!
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See if THIS helps. I haven't used NIO yet, but the steps here make sense. Sending objects would be much the opposite ... serialize to a byte array output stream, put the byte array to the byte buffer, etc.
 
merwin pinto
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Thanks a lot for the prompt response.
thanks to Stan James .... i will go thru the link you gave . It looks promising!!
 
merwin pinto
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
-----------------------------------------------------------------------



if (currentSelectionKey.isReadable()) {
ByteBuffer bb = ByteBuffer.allocate(30);
int bytesRead = ((SocketChannel) currentSelectionKey.channel()).read(bb);
if (bytesRead > 0) {
bb.flip();
persistentBuffer.addBytes(bb); //persistentBuffer contains only bytes added here, in excactly the order they were read
Object o = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(persistenBuffer.array());
ObjectInputStream ois = new ObjectInputStream(bais);
Object o = ois.readObject();
} catch (Exception ignored);
if (o != null) {
//perform any further actions on this received object
}
}
-----------------------------------------------------------------------

Hi,
Suppose i have an object ...... MyObject my=new MyObject();
how do i convert it to an byte array? To send the object should i create
a Channel at the client end and send using a ByteBuffer ?

I tried to send the object using
ObjectOutputStream ois=new ObjectOutputStream(socket.getOutputStream());
and ois.writeObject(obj);
...... Now this throws a stream corrupted exception
any suggestions ??
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!