tags:

views:

54

answers:

1

Hi Coders,
I have got a problem in here...!

I want to write a program in which I have to pass some data and packet_no of that data...

So, I am creating an class Packet. I want to send the an Packet object through the OutputStream of the Socket.

How do I achieve this?
Thanks

+6  A: 

The thing, that you need, is called an ObjectOutputStream. it is created from the regular OutputStream. At the reciever side you will need the appropirate ObjectInputStream. Your object and all of it fields must implement Serializable interface.

Example code:

OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(p);
Frozen Spider
+1 for writing a short concise answer to such a generic question. Just make sure that `class Packet` implements `Serializable`.
Isaac
They do not need a serialVersionUID, it will be calculated by the Serialization code. In fact, I believe you *should not* include a serialVersionUID unless you have thought about object versioning and what you're going to do about it. By that I mean what will you do when you receive an object from somewhere that was based on the code as it was last year? Will you convert it to the new structure? By specifying a serialVersionUID without giving this any thought, you are putting your head in the sand and hoping the problem won't arise.
Adrian Pronk
@Adrian Pronk Corrected
Frozen Spider
@Adrian Pronk not quite agreed. You are usually assigning the generated value that would otherwise be generated without you seeing it. However when the structure changes even a little, you have a problem. It's no surprise eclipse warns about not defining the uid.
Bozho
@Bozho: There is no value in assigning the "generated value that would otherwise be generated without you seeing it", you might as well assign it the value zero -- unless you've already got serialized objects in the wild that used the generated value. I agree, when the structure changes just a little you have a problem. But if you've manually set the serialversionUid, you won't realise it because Java won't complain. But if you omit the serialVersionUid and let it default, deserialization will blow up with an exception to remind you to do something about it.
Adrian Pronk
That depends on whether one understands the serialization mechanism :)
Bozho
The point is that once you do have serialized objects in the wild it is already too late to start thinking about versioning and serialVersionUIDs. You need to consider all this up front. Your advice to ignore the issue is seriously flawed. Also this post doesn't saynanything about serialVersionUD
EJP