简体   繁体   中英

class not found exception when sending objects through socket in java

SimpleClient.java

import java.net.*;
import java.io.*;

class testobject implements Serializable {

    int value;
    String id;

    public testobject(int v, String s) {
        this.value = v;
        this.id = s;
    }
}

public class SimpleClient {

    public static void main(String args[]) {
        try {
            Socket s = new Socket("localhost", 2002);
            OutputStream os = s.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            testobject to = new testobject(1, "object from client");
            oos.writeObject(to);
            oos.writeObject(new String("another object from the client"));
            oos.close();
            os.close();
            s.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

SimpleServer.java

import java.net.*;
import java.io.*;

class testobject implements Serializable {

    int value;
    String id;

    public testobject(int v, String s) {
        this.value = v;
        this.id = s;
    }
}

public class SimpleServer {

    public static void main(String args[]) {
        int port = 2002;
        try {
            ServerSocket ss = new ServerSocket(port);
            Socket s = ss.accept();
            InputStream is = s.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            testobject to = (testobject) ois.readObject();
            if (to != null) {
                System.out.println(to.id);
            }
            System.out.println((String) ois.readObject());
            is.close();
            s.close();
            ss.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

From the fact that you've repeated the testobject class in your post, it is evident that you think you can use two copies of it. You can't. You have to use the same one at both ends, in the same package. Preferably the same binary.

NB readObject() only returns null if you sent a null.

As @EJP mentioned, the client and server should use same testobject class file.

To verify it, add System.out.println("From client: " + to) and System.out.println("From server: " + to) to print full path name of object combined both package name and Class name.

Also, you can use keyword instance of to make sure the class type of object is what you want before using it.

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