简体   繁体   中英

Sending objects via java sockets

I am trying to send a object of the following class using java sockets:

public class CommunicationObj implements Serializable{
    private String ID;
    public AuthenticationParams s = new AuthenticationParams();
    public CommunicationObj(String s){
        ID = s;
    }
    public String getID(){
        return ID;
    }
}

But sending an object of the following class raises exception (unable to send the object), but the following code works

public class CommunicationObj implements Serializable{
    private String ID;

    public CommunicationObj(String s){
        ID = s;
    }
    public String getID(){
        return ID;
    }
}

Why AuthenticationParams object is creating such a problem here? Any help will be appreciated. Note: All the classes and packages used are identical to both server and client.

If any part of AuthenticationParams or AuthenticationParams itself is not marked as serializable, your serialization will fail.

In fact, every part of every part of your class must be serializable, or fields that for some reason cannot be serialized should be given the transient modifier, which indicates that that object should not be included in the serialization process.

AuthenticationParams class might not be serializable. You can add transient modifier to discard it from serialization like:

public transient AuthenticationParams s = new AuthenticationParams();

But if you want to include this object in the serialized form then you have no way but make AuthenticationParams class serializable.

Rule of Serialization: All non-transient objects referenced from the instance (the object instance which you want to serialize) must also be serializable.

Not: You can make use of java.io.Externalizable interface to develop your custom serialization mechanism.

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