简体   繁体   中英

Sending an object via sockets java

How can I send objects of a class via sockets? As of now I'm only able 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 Eg

   InputStream is = socket.getInputStream();   
   ObjectInputStream ois = new ObjectInputStream(is);   
   MyObject obj = (MyObject)ois.readObject();  
   //Now use the object

    Where:  
    class MyObject implements Serializable {  
      //variables
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM