如何使用WebSocket客户端监听REST API。

huangapple go评论64阅读模式
英文:

How do listen rest api with websocket client

问题

基本上,我想要监听我的 REST API 调用。就像当有人向我的 REST API 发送数据时一样。 (例如:http://localhost:8080/api/people)。然后 WebSocket 客户端会监听并可以从该地址获取响应,如果有人调用了那个地址。(就像当您使用 Postman 从 REST API 获取响应时,WebSocket 客户端也可以监听该响应)。我有点迷失,不知道如何使用 WebSocket 客户端来监听我的 REST API。我尝试过 "java Socket",但是我会得到 "connectionjava.net.UnknownHostException" 错误。有任何建议或示例,以及如何创建能够监听 REST API 的 WebSocket 客户端吗?WebSocket 客户端必须是一个简单的 Java 程序,可以从命令行运行。

英文:

Basically i want to listen my rest api calls. Like when somebody is sending data to my rest api. (ex: http://localhost:8080/api/people) Then websocket client listen and can get response from that address, if somebody is call that address. (like when you use postman to get response from rest api then websocet client can listen that response to.). I am littlebit lost, i dont know how to listen my rest api with websocket client. i have tried "java Socket" but then i get connectionjava.net.UnknownHostException error. Any suggestions or example how do create that websocket client that can listen rest api? Websocken client have to be simple java program that can be run from cmd.

答案1

得分: 1

你可以使用 javax.websocket 并实现一个端点(endpoint)。然后可以连接到此端点。当连接成功时,你可以将会话以同步方式保存(例如使用 CopyonWriteList<T>)。当调用你的 REST API 时,你可以访问 WebSocket 会话列表,并将你想要作为 REST API 响应返回给 WebSocket 客户端的数据发送过去。我不知道你正在使用什么框架,但你也可以使用切面(aspects)。

英文:

you can use javax.websocket and implement an endpoint. you can then connect to this endpoint. when you connect, you can save your session as well in a synchronized way (CopyonWriteList&lt;T&gt; for example). When your REST API is called, you can access the list of WebSocket sessions and send the data you want to return as your response of REST API back to the WebSocket client. I don't know what framework you are using, but you can also use aspects.

huangapple
  • 本文由 发表于 2020年4月8日 06:58:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/61090748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定