Skip to main content

Sending serialized object using sockets

2 replies [Last post]
anegri
Offline
Joined: 2007-07-26
Points: 0

Hi,

I did a network application and it works fine over sockets when senting strings, but as soon as I tried to send a simple object:

public class SerializableSample implements Serializable {

String name;

public SerializableSample() {

}

public SerializableSample(String name) {
this.name = name;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}

}

I get errors when trying to create the ObjectInputStream from the InputStream, based on a StreamCorruptedExcpetion on an invalid stream header.

ObjectInputStream ois = new ObjectInputStream(inputStream);
if (ois.available() > 0) {
Object obj = ois.readObject();
System.out.println(obj);
ois.close();
fireReaderEvent(obj);
}

I would really want to know if anyone is able to send serializable objects through the client / server sockets or should I change and use the bidirectional pipes instead?

Many thanks,
Alex

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
anegri
Offline
Joined: 2007-07-26
Points: 0

errr..... I think it might be on my code and NOT an issue with JXTA sockets.... I just modified the server/client socket sample and got it to work with a set of SerializableSample object. Will update once I narrow down the issue... any ideas would be again greatly appreciated.

hisham1
Offline
Joined: 2007-07-26
Points: 0

try this:

public synchronized void send(Object obj) {

try {
byte[] data = objectToBytes(obj);

out.write(data); // **out = soc.getOutputStream();**

out.flush();

sent++;

} catch (Exception io) {

System.out.println(io.getMessage() + " can't send the Message");
}

}

public byte[] objectToBytes(Object object) throws

IOException {

java.io.ObjectOutputStream out;

java.io.ByteArrayOutputStream bs;

bs = new java.io.ByteArrayOutputStream();

out = new java.io.ObjectOutputStream(bs);

out.writeObject(object);

out.close();

return bs.toByteArray();

}

Cheers,

Hisham Khalil

Message was edited by: hisham1