简体   繁体   中英

Java networking Serialization is failing on serializable object

I am working on a simple client/server program and for now all it is supposed to do is send an object from the client to the server on connection, then send an object from the server containing a response.

My object is supposed to send a username and password. Yes, I know there are other ways of authenticating a TCP connection, but this is a test to help me get my feet wet in networking with java.

My object is written as follows:

   import java.io.Serializable;

public class AuthAccount implements Serializable{
    private static final long serialVersionUID = -8918729105550799244L;
    private String username;
    private String password;

    AuthAccount(String user, String pass){
        username = user;
        password = pass;
    }
    String username(){
        return username;
    }
    String password(){
        return password;
    }
}

Socket connection is successful, but it fails on this line ( oos is ObjectOutputStream ):

System.out.print("Sending login object to server...");
oos.writeObject(new AuthAccount("user", "password"));
System.out.println("Done!");

I keep receiving the error:

java.io.NotSerializableException: AuthAccount

I have tried the AuthAccount test class using char[] username = new char[30]; so as to have a fixed size object. I am more of a C++ guy, but java made sense to me for this project.

You must be using an old version of your build because

public class Main {
    public static void main(String... args) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(new AuthAccount("u", "p"));
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
        Object aa = ois.readObject();
    }
}
 class AuthAccount implements Serializable{
    private static final long serialVersionUID = 1;
    private final String username;
    private final String password;

    AuthAccount(String user, String pass){
        username = user;
        password = pass;
    }
    String username(){
        return username;
    }
    String password(){
        return password;
    }
}

runs without error.

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