如何通过Java套接字发送对象(Java网络)并读取对象

时间:2018-08-16 12:59:21

标签: java sockets inputstream classnotfoundexception outputstream

我想使用Java网络制作聊天应用程序。到目前为止,我已经在两个不同的项目中创建了服务器和客户端类,并且它们每个都有相同的Message类:

package client;

import java.io.Serializable;

public class Message implements Serializable {

public static final long serialVersionUID = 1l;

private String text;
private int receiversID;
private int senderID;

public Message(String text, int receiversID, int senderID){
    this.text = text;
    this.receiversID = receiversID;
    this.senderID = senderID;
}

public String getText() {
    return text;
}

public int getReceiversID() {
    return receiversID;
}

public int getSenderID() {
    return senderID;
}

比起我在客户端类中发送一条消息来说,

            do {
            System.out.print("Enter message to be sent: ");
            text = scanner.nextLine();
            System.out.print("Enter receivers ID: ");
            receiverID = scanner.nextInt();

            outputStream.writeObject(new Message(text, receiverID, ID)); // sending message
            outputStream.flush();

            if (!text.equals("exit")) {
                try {
                    Message message = (Message) inputStream.readObject();
                    System.out.print(message.getText() + "\n");
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
        } while (!text.equals("exit"));

当我想在服务器项目中获取该消息时发生错误:

        Message message = (Message) inputStream.readObject();

我明白了:

java.lang.ClassNotFoundException: client.Message
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
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:683)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1863)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1746)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2037)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1568)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:428)
at network.ClientSockets.run(ClientSockets.java:57)

我知道服务器项目无法识别来自客户端的Message类,尽管它们是相同的类,但是我真的不知道该如何解决。

有人知道解决方案吗?

0 个答案:

没有答案