Sending an object via sockets java
How can I send objects of a class via sockets? As of now I'm only ab开发者_开发百科le to send the class members one by one via sockets and I want to send the object as a whole. Explaining with a simple example would be great. Thanks.
You must use the java.io.Serializable
interface for the objects you want to transer.
Then ObjectInputStream
or ObjectOutputStream
to readObject
or writeObject
E.g.
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
MyObject obj = (MyObject)ois.readObject();
//Now use the object
Where:
class MyObject implements Serializable {
//variables
}
精彩评论