使用套接字在客户端-服务器应用程序中发送数据的最佳方式
嘿,我想做的是客户端上的一个 Swing 应用程序(使用套接字)执行某些操作,以及服务器端的另一个应用程序(使用 serverSocket)根据请求执行所有数据库工作。我已阅读有关套接字的内容以及如何使用它们,我主要关心的是哪种是发送数据的最佳方式。
可以说,我有一个用户集合,我想将其发送到客户端进行显示。发送它的最佳方式是什么?我考虑过序列化集合并将其发送到客户端,但我无法转换为类型(java.util.ArrayList)(只是一个例子),因为我不知道客户端应用程序中的用户类,并且我无法访问用户特定的方法。这就提出了一个问题:我应该知道客户端应用程序中的用户吗?客户端应用程序?所以任何建议都是好的。
附言。对于数据检索,我使用 Hibernate。
Hy, what i am trying to do is an Swing App(using sockets) on the client side that does something , and another App for the server(using serverSocket) which does all the database work according to the request.I have read about sockets and how to use them , my main concern is which is the best way to send data.
Lets just say that i have a collection of users and i want to send it to the client to be shown .Which is the best way to send it ?I thought about serializing the collection and sending it to the client , but i cannot cast to the type (java.util.ArrayList) (just an example) because i don`t know about the user class in the client App,and i cannot access the users specific methods.That raises the question :should I know about the Users in the client App? So any sugestions are good.
PS. For data retrieve i use Hibernate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要扩展@JB Nizet,RMI 会更容易。 JMX 会更容易。 Web 服务会容易得多。
基本上,这个问题在大多数用例中都已“解决”,您应该查看这些技术和框架,而不是原始套接字。除非您有真正特定的需求(而且大多数情况下根本没有),否则套接字只是浪费时间。
Web 服务、POX over HTTP、远程 EJB、远程 JMX、RMI 以及其他一切都可以为您处理所有这些。这个轮子不需要重新发明。
使用 Glassfish 或 Tomcat + JAX-WS,然后就可以完成了。写一些逻辑来解决问题,让世界变得更美好,而不是多年前就想出来的管道。
To expand on @JB Nizet, RMI would be easier. JMX would be easier still. Web services would be MUCH easier.
Basically, this problem is "solved" for the VAST majority of use cases, and you should be looking at those technologies and frameworks rather than raw sockets. Unless you have a really specific need (and most simply don't), sockets are a waste of time.
Web Services, POX over HTTP, Remote EJBs, Remote JMX, RMI and everything else deal with all of this for you. This wheel does not need to be reinvented.
Grab Glassfish or Tomcat + JAX-WS, and be done with it. Write some logic to solve a problem and make the world a better place instead of plumbing that's been figured out years ago.
为了能够反序列化一个对象,您需要在类路径中拥有该对象的具体类(以及递归地该对象引用的所有对象的具体类)。所以是的,客户端需要在其类路径中包含 User 类。
您是否考虑过使用 RMI 而不是使用普通套接字?这可能会容易得多。
To be able to deserialize an object, you need to have the concrete class of the object (and, recursively, of all the objects referenced by the object) in the classpath. So yes, the client needs the User class in its classpath.
Have you thought about using RMI instead of using plain sockets? This would probably be much easier.
您可以序列化到一些中间体(xml、json 等),将其推送到套接字并绑定回您的客户端理解的 java 类。
You could serialize to some intermediat(xml,json,etc.) push that across the socket and bind back to java classes that your client understands.