简体   繁体   中英

Java send object with TCP

我用Java在不同的项目中制作了一个简单的TCP服务器和客户端。当我尝试将字符串发送到服务器时,它可以工作,但是我想将对象发送到服务器。我为该对象创建了类,并使其可序列化,但是服务器和客户端位于不同的项目中,那么如何使服务器和客户端能够识别要发送的对象?我试图将这两个类放在同一项目中的不同包中,但是这样我只能运行服务器或客户端,而不是两者兼有。那么如何将对象从客户端传递到服务器?

If you use Java Serialization, you have to have the same class with the same name and ideally the same version at both ends. This is not something you can change with Java Serialization. If you want to do custom serialization you can do this, but this is not the easy way out.

I suggest you have a Jar with your data transfer objects and you share this jar with both the client and server and this will make it easier to ensure they are the same.

Split your project into three jars, client, sever and shared .

Put the transfer objects into the shared jar and deploy it on both client and server. For serialization to work you need to have the serialized classes available on both ends class pathes (and they need to be exactly identical in qualified name, that means same package and same classname ).

Server and Client are two different (but similar) things. The server is there to wait for incoming requests by clients, and the clients does just that, requests things to the server.

For your Server and Client to work well there might be some conditions:

  1. The Server is running
  2. The Client knows the Server's IP and port number

See this thread for an easier and up to date solution to send objects via TCP in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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