Search code examples
javaobjectinputstream

Java ObjectInputStream (server\client)


server thread

package schatserver;

public ServerThread(Socket socket) {
        this.socket = socket;
        this.start();
    } 



 public void run() {
        try {
             ObjectInputStream inputStream = new ObjectInputStream(this.socket.getInputStream());
              ObjectOutputStream outputStream = new ObjectOutputStream(this.socket.getOutputStream());
        container = (Message) inputStream.readObject();  
        .....
        ..... etc

and "Message class" contains at both server side and client side

public class Message implements Serializable {

private String login;
private String message;
private String[] users;
private Date time;

public Message(String login, String message){ //for client
        this.login = login;
        this.message = message;
        this.time = java.util.Calendar.getInstance().getTime();
    }


 public Message(String login, String message, String[] users){//for server
        this.login = login;
        this.message = message;
        this.time = java.util.Calendar.getInstance().getTime();
        this.users = users;
    }

trying sending Object "Message"

private static Message message;

public void Connect() {
        try {            
            sock = new Socket(ClientConfig.HOST, ClientConfig.PORT);
            System.out.println("Connected with: " + ClientConfig.HOST);                        
            ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
            out.writeObject(message);
            out.flush();

getting "java.lang.ClassNotFoundException: socketchatclient.Message" at this line

 container = (Message) inputStream.readObject();  

can someone explain me how should i send Object Message?

socketchatclient. - it's client package


Solution

  • java.lang.ClassNotFoundException: socketchatclient.Message

    It means you are trying to deserialize a class you don't have. Most likely the code on your client is different to that on the server and the client has serialized a class it has but unless the server also has this class in the same package it cannot deserialize it.

    I suggest you have a common module for serializable objects and both the client and server share to ensure the same classes are available at both ends.