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()
仅当您发送 null 时才返回 null。
关于java - java中通过socket发送对象时未找到类异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38674056/