我正在开发一个可以处理对象输入和输出流的简单套接字程序。尝试从输入流中读取对象时遇到问题。我猜我的自定义类有问题,但仍无法解决问题。
ServerRequest request =(ServerRequest)ois.readObject();
错误:
ServerThread run
SEVERE: null
java.lang.ClassNotFoundException: ss_client.ServerRequest
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:686)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1866)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1749)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2040)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1571)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
at ServerThread.run(ServerThread.java:31)
客户方:
Socket socket = new Socket("localhost",1688);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ServerRequest request = new ServerRequest("test", "clientConnect", "something");
oos.writeObject(request);
System.out.println("connection sent");
ServerResponse response = (ServerResponse)ois.readObject();
System.out.println(response.body);
socket.close();
服务器端:
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
ServerRequest request = (ServerRequest) ois.readObject();
switch (request.header) {
case "clientConnect":
System.out.println(client.getInetAddress() + " is connected!");
ServerResponse response = new ServerResponse(200, client.getInetAddress().getHostAddress(), "test", "clientConnect", "debug");
oos.writeObject(response);
break;
client.close();
ServerRequest类:
public class ServerRequest implements Serializable {
private static final long serialVersionUID = 42L;
public String senderIP;
public String senderUsername;
public Timestamp timestamp;
public String header;
public Object body;
ServerRequest(String senderUsername, String header, Object body) throws UnknownHostException {
this.senderIP = InetAddress.getLocalHost().getHostAddress();
this.senderUsername = senderUsername;
this.timestamp = new Timestamp(System.currentTimeMillis());
this.header = header;
this.body = body;
}
...setters and getters...
}