简体   繁体   English

通过java中的套接字发送对象时,找不到类未找到异常

[英]class not found exception when sending objects through socket in java

SimpleClient.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 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. 从您在帖子中重复了testobject类的事实来看,很明显,您认为可以使用它的两个副本。 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. 注意: readObject()仅在发送空值时返回空值。

As @EJP mentioned, the client and server should use same testobject class file. 如@EJP所述,客户端和服务器应使用相同的testobject类文件。

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. 要对其进行验证,请添加System.out.println("From client: " + to)System.out.println("From server: " + to)以打印组合了包名和类名的对象的完整路径名。

Also, you can use keyword instance of to make sure the class type of object is what you want before using it. 另外,您可以使用关键字instance of来确保对象的类类型是您想要的,然后再使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM