简体   繁体   English

通过套接字Java发送对象

[英]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. 您必须对要转换的对象使用java.io.Serializable接口。
Then ObjectInputStream or ObjectOutputStream to readObject or writeObject Eg 然后将ObjectInputStreamObjectOutputStream改为readObjectwriteObject

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

    Where:  
    class MyObject implements Serializable {  
      //variables
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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