英文:
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<T>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论