REST服务器到客户端的通信(REST Server to client communication)

编程入门 行业动态 更新时间:2024-10-25 21:19:19
REST服务器到客户端的通信(REST Server to client communication)

我正在为Spring中的Adndroid应用程序开发Java API。 现在我的API是100%REST和无状态。 要使客户端接收数据,它必须先发送请求。

但是,我需要的是服务器将数据发送到客户端 /而不是客户端到服务器fisrt /当它准备好它的任务时。

我认为必须在双方之间建立某种形式的会话。

我的问题是:当它准备好执行任务时,如何实现SERVER向CLIENT发送数据的这一功能? /不知道任务需要多长时间./

我应该为此目的开发什么样的API?

一个愚蠢的解决方法是每隔n秒向服务器发送一个请求,但我正在寻求更智能的方法。

I'm developing a Java API for an Adndroid app in Spring. Right now my API is 100% REST and stateless. For the client to receive data, it must send a request first.

However, what I need is the server to send data to the to the client /not the client to the server fisrt/ whenever it is ready with it's task.

I think that some kind of session must be created between the two parties.

My question is: How can I achieve this functionality of the SERVER sending data to the CLIENT when it's ready with it's task? /It is unknown how long the task will take./

What kind of API should I develop for this purpose?

One idiotic workaround is sending a request to the server every n seconds but I'm seeking for a more intelligent approach.

最满意答案

有多种选择。 您可以选择最适合您的选择。

Http Long Polling - 在这种情况下,服务器保留请求,直到它完成任务(在您的情况下)。 在这里,您不必每隔几秒钟发出多个请求(这是Http轮询)。

服务器发送事件 - 在此,服务器将更新发送到客户端而不进行长轮询。 它是HTML 5的标准化部分 - https://www.w3.org/TR/eventsource/

Websockets - 好吧,websockets在双工模式下工作,并在此建立持久的TCP连接。 建立TCP连接后,服务器和客户端都会来回发送数据。 大多数现代浏览器支持。 您可以检查Android Websocket Library,如autobahn和Java websocket。

SockJs - 我建议使用此选项而不是普通的WebSocket。 http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#websocket-fallback-sockjs-enable

There are multiple options available. You can choose what suits best for you.

Http Long Polling - In this, server holds the request until it's ready with its task (in your case). Here, you don't have to make multiple requests every few seconds (Which is Http Polling).

Server Sent Events - In this, server sends update to the client without long-polling. It is a standardized part of HTML 5 - https://www.w3.org/TR/eventsource/

Websockets - Well, websockets work in duplex mode and in this a persistent TCP connection is established. Once TCP connection is established, both server and client sends data to and fro. Supported by most modern browsers. You can check for Android Websocket Library like autobahn and Java websocket.

SockJs - I would recommend to go with this option instead of plain WebSocket. http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#websocket-fallback-sockjs-enable

更多推荐

本文发布于:2023-08-03 16:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1395133.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   通信   服务器   REST   client

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!