简体   繁体   English

如何在Java中通过TCP发送对象?

[英]How to send an OBJECT over TCP in java?

I'm writing a program to send an object from one class to another class. 我正在编写一个程序,将一个对象从一个类发送到另一个类。 Here is a short sample example of my program to represent the problem. 这是我的程序代表问题的简短示例。 As you can see the object to send from server to client is Student class which has been defined separately in each class(Server/Client). 如您所见,从服务器发送到客户端的对象是Student类该类已在每个类(服务器/客户端)中分别定义。 I have examined this code by sending an ArrayList which works fine but when it comes to a class type which defined by myself i'm receiving this error: 我已经通过发送正常工作的ArrayList检查了此代码,但是当涉及到由我自己定义的类类型时,我收到此错误:

Exception in thread "main" java.lang.ClassCastException: ServerSide$1Student cannot be cast to ClientSide$1Student
    at ClientSide.main(ClientSide.java:29)

Here is the code for Server side: 这是服务器端的代码:

import java.io.*;
import java.net.*;

public class ServerSide {

    public static void main(String[] args) {
        class Student implements Serializable
        {
            int id;
            public Student(int num){id=num;}
            public void setID(int num){id=num;}
            public void Print(){System.out.println("id = " + id);}
        }
        try
        {
            Student a = new Student(3);
            ServerSocket myServerSocket = new ServerSocket(9999);
            Socket skt = myServerSocket.accept();   
            try 
            {
                ObjectOutputStream objectOutput = new ObjectOutputStream(skt.getOutputStream());
                objectOutput.writeObject(a);                
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            } 
        }
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

And for the client side is: 对于客户端而言:

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSide {

    public static void main(String[] args)
    {
        class Student implements Serializable
        {
            int id;
            public Student(int num){id=num;}        
            public void setID(int num){id=num;}
            public void Print(){System.out.println("id = " + id);}
        }
        try {       
            Socket socket = new Socket("10.1.1.2",9999);
            try {
                ObjectInputStream objectInput = new ObjectInputStream(socket.getInputStream());
                try {
                    Object object =(Student) objectInput.readObject();
                    Student tmp = (Student) object;
                    tmp.Print();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }           
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }   
    }   
}

Edit: 编辑:

I moved them to same file and added serialise ID. 我将它们移到同一文件并添加了序列化ID。 It works fine. 工作正常。

Having two classes with the same name is not enough. 仅具有两个名称相同的类是不够的。 The two classes need to have 这两个班需要

  • the same package 同一包
  • be in the same outer class if any 在同一个外层阶级(如果有)
  • have the same serialVersionUID. 具有相同的serialVersionUID。

I suggest you have a single, stand alone class which is common for both the client and the server. 我建议您有一个单独的类,对于客户端和服务器都是通用的。 In a more complex project you might consider building these common components in a module which both the client and server modules depend on. 在更复杂的项目中,您可能会考虑在客户端和服务器模块都依赖的模块中构建这些通用组件。

You cannot ever deserialize a stream representing an instance of class X into an instance of class Y. 您永远无法将代表类X的实例的流反序列化为类Y的实例。

To solve your problem, you need to move the code for the Student class to another file, say Student.java, and use that single class on your client code and on your server code. 为了解决您的问题,您需要将Student类的代码移动到另一个文件,例如Student.java,并在客户端代码和服务器代码上使用该单个类。

Note that if you modify your class, in most cases you will need to redeploy the server (otherwise the client would send the server an stream representing an instance of class that is known only to the client). 请注意,如果您修改类,则在大多数情况下,您将需要重新部署服务器(否则客户端将向服务器发送一个流,该流表示仅客户端知道的类实例)。

You are referencing two different classes. 您正在引用两个不同的类。 Student which is an inner of ClientSide and Student which is an inner class of ServerSide . StudentClientSide的内部, StudentServerSide的内部类。 You should move the Student class to a different file. 您应该将Student类移动到其他文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM