在java中通过套接字发送对象
我有2个java netbeans项目,一个是服务器,另一个是客户端。我有一个我创建的 Message 类,我想在服务器上完成修改后将其传递给服务器,并以另一种方式将其传递回客户端。我已经在两个项目中都包含了类消息。我使用并传递对象。服务器和客户端之间的连接是正常的,对象通过,但是在服务器上,当我从 using 方法读取对象时,我键入将其转换为类。但是一个ClassNotFoundException被扔在服务器上。它找不到 Message 类。如何解决此问题?ObjectOutputStream
ObjectInputStream
ObjectInputStream
readObject()
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的解决方案?