簡體   English   中英

通過java中的套接字發送對象時,找不到類未找到異常

[英]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);
        }
    }
}

從您在帖子中重復了testobject類的事實來看,很明顯,您認為可以使用它的兩個副本。 你不能 您必須在同一包裝的兩端使用相同的包裝。 最好是相同的二進制文件。

注意: readObject()僅在發送空值時返回空值。

如@EJP所述,客戶端和服務器應使用相同的testobject類文件。

要對其進行驗證,請添加System.out.println("From client: " + to)System.out.println("From server: " + to)以打印組合了包名和類名的對象的完整路徑名。

另外,您可以使用關鍵字instance of來確保對象的類類型是您想要的,然后再使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM