在java中通过套接字发送对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19217420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 15:10:02  来源:igfitidea点击:

Sending an object through a socket in java

javasockets

提问by Kasun Kodagoda

I have 2 java netbeans projects, one is the Server other is the Client. I have a Message class that I have created which I want to pass to the server and back the other way to the client after modification done at the server. I have included the class Message in both projects. I use ObjectOutputStreamand ObjectInputStreamto pass the object. The connection between the server and the client is ok and the object passes through but at the server when I read the object from the ObjectInputStreamusing readObject()method I type cast it to the Messageclass. But an ClassNotFoundExceptionis thrown at the server. It cant find the Message class. How can I resolve this?

我有 2 个 java netbeans 项目,一个是服务器,另一个是客户端。我创建了一个 Message 类,我想将其传递给服务器,并在服务器上完成修改后以另一种方式返回给客户端。我在两个项目中都包含了 Message 类。我使用ObjectOutputStreamObjectInputStream传递对象。服务器和客户端之间的连接正常,对象通过,但是在服务器上,当我从ObjectInputStreamusingreadObject()方法读取对象时,我将其转换为Message类。但是在服务器上抛出了ClassNotFoundException。它找不到 Message 类。我该如何解决这个问题?

Code for the client:

客户端代码:

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());
    }
}

Code for the Server

服务器代码

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());
    }
}

The exception thrown at the "server"

在“服务器”抛出的异常

java.lang.ClassNotFoundException: rusl.online.examination.system.client.utility.Message

Would I have to use java RMI? Is there a solution for this without using RMI?

我必须使用 java RMI 吗?有没有不使用 RMI 的解决方案?

采纳答案by Evgeniy Dorofeev

Make sure that Message on server side is rusl.online.examination.system.client.utility.Message. It seems not to be the case.

确保服务器端的 Message 是rusl.online.examination.system.client.utility.Message. 情况似乎并非如此。

回答by Sorter

If you are sending objects of a class over the socket. In order to reproduce the object at the other end, you have to cast the object. For that you will require the class definition on both ends.

如果您通过套接字发送类的对象。为了在另一端重现对象,您必须投射对象。为此,您将需要两端的类定义。

Make sure you properly import the same Messageclass for server program as well, which you used to create the message.

确保您也Message为服务器程序正确导入了用于创建消息的相同类。