KG6ZVP
KG6ZVP

Reputation: 3579

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.

Upvotes: 1

Views: 791

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533820

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.

Upvotes: 3

Related Questions