Java 中的客户端服务器通信 - 使用哪种方法?
我有一个典型的客户端服务器通信 - 客户端将数据发送到服务器,服务器处理该数据,然后将数据返回给客户端。问题是该过程操作可能需要相当长的时间(数量级)——几分钟。有几种方法可以用来解决这个问题。
- 建立连接并保持连接状态,直到操作完成并且客户端收到响应。
- 建立连接、发送数据、关闭连接。现在处理开始了,一旦完成,服务器就可以建立到客户端的连接来发送数据。
- 建立连接、发送数据、关闭连接。进行处理。客户端每隔 n 分钟/秒询问服务器操作是否完成。如果处理完成,客户端将获取数据。
我想知道哪种方法是最好的使用方法。是否有一些“事实上的”标准来解决这个问题?在 Java 中打开套接字有多“昂贵”?解决方案 1. 对我来说似乎很糟糕,但 2. 和 3. 可以。解决方案 2. 的问题在于服务器需要知道客户端正在侦听哪个端口,而解决方案 3. 则增加了一些网络开销。
I have a typical client server communication - Client sends data to the server, server processes that, and returns data to the client. The problem is that the process operation can take quite some time - order of magnitude - minutes. There are a few approaches that could be used to solve this.
- Establish a connection, and keep it alive, until the operation is finished and the client receives the response.
- Establish connection, send data, close the connection. Now the processing takes place and once it is finished the server could establish a connection to the client to send the data.
- Establish a connection, send data, close the connection. Processing takes place. client asks server, every n minutes/seconds if the operation is finished. If the processing is finished the client fetches the data.
I was wondering which approach would be the best way to use. Is there maybe some "de facto" standard for solving this problem? How "expensive" is opening a socket in Java? Solution 1. seems pretty nasty to me, but 2. and 3. could do. The problem with solution 2. is that the server needs to know on which port the client is listening, while solution 3. adds some network overhead.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
打开套接字有时很昂贵,但并不像数据处理那么昂贵。
Opening sockets is sometimes expensive, but not so expensive that your data processing.
我发现选项 2 存在一个直接问题。如果客户端位于防火墙后面,他很可能会被允许连接并执行请求,但服务器可能会被阻止连接回客户端。
正如你所说,选项 1 看起来有点令人讨厌(不过不是太讨厌,可以很好地工作),所以在列出的选项中,我会选择选项 3。也许服务器可以估计处理的剩余时间,并提示在每次民意调查中,客户都会知道何时需要回来查看。
I see an immediate problem with option 2. If the client is behind a firewall, he might very well be allowed to connect and do the request, but the server might be prevented to connect back to the cilent.
As you say, option 1 looks a bit nasty (not too nasty though, could work well), so among the options listed, I would go for option 3. Perhaps the server could estimate the time that's left of the processing, and hint the client, in each poll, of when it's about time to check back.