ObjectOutputStream
和ObjectInputStream
来传递对象。服务器和客户端之间的连接是正常的,对象通过但在服务器上,当我使用ObjectInputStream
方法从readObject()
读取对象时,我将其输入到Message
类。但是服务器会抛出 ClassNotFoundException 。它找不到Message类。我该如何解决这个问题?
客户代码:
public void startClient() {
try {
// Create the socket
Socket clientSocket = new Socket(HOST, PORT);
// Create the input & output streams to the server
ObjectOutputStream outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream inFromServer = new ObjectInputStream(clientSocket.getInputStream());
// Read modify
// TODO here
/* Create The Message Object to send */
LinkedList<Message> msgList = new LinkedList<>();
Message msg = new Message();
msg.setMessage("Kasun");
msg.setIndex(1);
msg.setAverage(5.5f);
msgList.push(msg);
/* Send the Message Object to the server */
outToServer.writeObject(msgList);
/* Retrive the Message Object from server */
LinkedList<Message> inFromServerList = new LinkedList<>();
Message msgFrmServer = null;
inFromServerList = (LinkedList<Message>)inFromServer.readObject();
msgFrmServer = inFromServerList.pop();
/* Print out the recived Message */
System.out.println("Message: " + msgFrmServer.getMessage());
System.out.println("Index: " + msgFrmServer.getIndex());
System.out.println("Average: " + msgFrmServer.getAverage());
clientSocket.close();
} catch (Exception e) {
System.err.println("Client Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
}
}
服务器代码
public void startServer() {
try {
ServerSocket welcomeSocket = new ServerSocket(PORT);
while (true) {
// Create the Client Socket
Socket clientSocket = welcomeSocket.accept();
System.out.println("Socket Extablished...");
// Create input and output streams to client
ObjectOutputStream outToClient = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream inFromClient = new ObjectInputStream(clientSocket.getInputStream());
// Read modify
// TODO here
/* Create Message object and retrive information */
LinkedList<Message> inList = new LinkedList<>();
Message inMsg = null;
inList = (LinkedList<Message>)inFromClient.readObject();
inMsg = inList.pop();
/* Modify the message object */
inMsg.setMessage(inMsg.getMessage().toUpperCase());
inMsg.setIndex(5);
inMsg.setAverage(10.5f);
/* Send the modified Message object back */
outToClient.writeObject(inMsg);
}
} catch (Exception e) {
System.err.println("Server Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
System.err.println("To String: " + e.toString());
}
}
“服务器”抛出的异常
java.lang.ClassNotFoundException: rusl.online.examination.system.client.utility.Message
我是否必须使用java RMI?有没有使用RMI的解决方案?
答案 0 :(得分:7)
确保服务器端的消息为rusl.online.examination.system.client.utility.Message
。似乎并非如此。
答案 1 :(得分:1)
如果要通过套接字发送类的对象。为了在另一端再现对象,您必须转换对象。为此,您将需要两端的类定义。
确保为服务器程序正确导入相同的Message
类,用于创建消息。