我有2個java netbeans項目,其中一個是Server其他的是客戶端。我有一個消息類,我已經創建了我想傳遞給服務器,並在服務器完成修改後以另一種方式返回到客戶端。我已經在這兩個項目中包含了類Message。我使用ObjectOutputStream
和ObjectInputStream
來傳遞對象。服務器和客戶端之間的連接正常,對象通過但在服務器上時,我使用readObject()
方法從ObjectInputStream
中讀取對象,並將其轉換爲Message
類。但是在服務器上拋出了ClassNotFoundException。它無法找到消息類。我該如何解決這個問題?在java中通過套接字發送對象
代碼客戶端:
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有沒有解決方案?
由於您*不是*使用RMI,它不是這個問題的適當標籤。 – EJP