简体   繁体   English

Java使用TCP发送对象

[英]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. 如果使用Java序列化,则必须具有相同名称的同一个类,并且最好两端具有相同的版本。 This is not something you can change with Java Serialization. 这不是您可以通过Java序列化更改的东西。 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. 我建议您有一个包含数据传输对象的jar,并与客户端和服务器共享此jar,这样可以更轻松地确保它们相同。

Split your project into three jars, client, sever and shared . 将您的项目分成三个jar,分别是客户端,服务器和共享

Put the transfer objects into the shared jar and deploy it on both client and server. 将传输对象放入共享jar中,并将其部署在客户端服务器上。 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 客户端知道服务器的IP和端口号

See this thread for an easier and up to date solution to send objects via TCP in Java. 请参阅此线程 ,以获取更简单,最新的解决方案,以Java中的TCP通过TCP发送对象。

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

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