简体   繁体   English

如何通过套接字发送和接收Java对象?

[英]How to send and receive Java objects over Sockets?

I'm coding a concurrent ATM application having a Client and a Server. 我正在编写一个具有客户端和服务器的并发ATM应用程序。

I need to know how Socket programming can be used in this to call Server methods (request for his current balance, transfer funds etc) and get Objects returned to Client. 我需要知道如何使用Socket编程来调用Server方法(请求他当前的余额,转移资金等)并将对象返回给客户端。

I do not want just to pass text using System.out.println like mentioned in Lesson: All About Sockets 我不想只使用System.out.println传递文本,如Lesson:All About Sockets中所述

You should use Javas RMI Lib for this. 你应该使用Javas RMI Lib。

You can find a small example here: http://download.oracle.com/javase/1.3/docs/guide/rmi/getstart.doc.html 你可以在这里找到一个小例子: http//download.oracle.com/javase/1.3/docs/guide/rmi/getstart.doc.html

You need to serialize your data, send it, and deserialize it. 您需要序列化数据,发送数据并对其进行反序列化。 See Lesson: Basic I/O for an introduction to the Java serialization classes. 有关Java序列化类的介绍,请参阅课程:基本I / O.

Sockets are just a way to open a communication channel between a server and a client. 套接字只是打开服务器和客户端之间通信通道的一种方式。 A socket connection just enables you to send bytes from one machine to the other, nothing more. 套接字连接只允许您将字节从一台机器发送到另一台机器,仅此而已。 In particular, sockets do not directly provide a way to call methods on another machine. 特别是,套接字不直接提供在另一台机器上调用方法的方法。

You will need to implement an application-level protocol on top of sockets, or use some existing (standard) application-level protocol. 您需要在套接字之上实现应用程序级协议,或使用某些现有(标准)应用程序级协议。 You could use RMI as suggested by ashiaka, or for example JAX-RS (Java's standard API for RESTful web services). 您可以使用ashiaka建议的RMI,或者例如JAX-RS (Java的RESTful Web服务的标准API)。 Both these will use sockets to get the data across from one machine to the other. 这两个都将使用套接字将数据从一台机器传递到另一台机器。

So yes, it is possible using sockets, but you need to use something on top of that to actually remotely call methods. 所以是的,它可以使用套接字,但你需要在其上使用一些东西来实际远程调用方法。

I found this tutorial really helpful http://java.sun.com/developer/technicalArticles/ALT/sockets/ 我发现本教程非常有用http://java.sun.com/developer/technicalArticles/ALT/sockets/

They say: 他们说:

RMI = Sockets + Object Serialization + Some Utilities RMI =套接字+对象序列化+一些实用程序

Thanks guys for contributing! 谢谢你们的贡献!

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

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