Spring Boot + Websocket(SockJS) [英] Spring Boot + Websocket (SockJS)

查看:571
本文介绍了Spring Boot + Websocket(SockJS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个服务器,以便在发生更改时通知已连接的客户端。
为此,我使用Spring Boot作为服务器。为了传递通知,每个客户端都与服务器建立套接字。
我使用了本指南: https://spring.io/guides/gs / messaging-stomp-websocket / 它完美无缺。在此示例中,客户端通过套接字发送消息,服务器响应。

I'm trying to make a server that notifies connected clients when changes occur. For that, I'm using Spring Boot for the server. In order to deliver notifications, each client establish a socket with the server. I used this guide : https://spring.io/guides/gs/messaging-stomp-websocket/ and it works perfectly. In this example, the client send a message over the socket and the server responds.


  1. 问题是我找不到服务器向客户端发送消息而不让客户端先发送消息的方式!

  2. 是否可以列出所有连接的websockets?

谢谢,

推荐答案

我的回答:


  1. 客户端不需要发送消息,但必须连接和订阅。我实际上是在浏览器连接和订阅然后开始发送消息的应用程序中自己做的。在服务器端,您可以使用SimpMessagingTemplate对象自动装配服务(或其他组件),然后使用convertAndSend系列函数将事物发送给特定用户或所有订户。如果您查看投资组合项目,您可以看到它是如何完成价格的。库存主题。客户端连接并订阅,服务器具有要发送给它的预定作业。此服务使用MessageSendingOperations对象,但您可以使用上面提到的SimpMessagingTemplate。我在我们的应用程序服务中有这个代码:

  1. The client does not need to send a message but they do have to connect and subscribe. I am actually doing that myself in an application where a browser connects and subscribes and then starts sending messages. On the server side you can Autowire a Service (or other Component) with a SimpMessagingTemplate object and then use the convertAndSend family of functions to send things to either a particular user or all subscribers. If you check out the portfolio project you can see how it is done with the price.stock topic. The client connects and subscribes and the server has a scheduled job to send to it. This service is using a MessageSendingOperations object but you can use SimpMessagingTemplate as mentioned above. I have this code in our application service:

@Autowired
private SimpMessagingTemplate messagingTemplate;

...
messagingTemplate.convertAndSendToUser(userId, destination, jsonMessage);


  • 这个问题提供了一些关于查找所有用户的好信息。您似乎需要使用关于STOMP上下文事件的Spring文档,以便在需要时自己跟踪事物。通常,因为这是订阅模型,您可能不需要知道谁连接。您还可以构建自己的主题,发出请求,让所有客户回复并查找他们的帖子。我自己没有这样做,但Rossen(其中一位评论员)是该项目的主要作者之一,所以我相信他!

  • This question has some good information on finding all users. It seems like you need to use the events defined in the Spring documentation on STOMP context events to keep track of things yourself if you want that. Generally since this is a subscription model you may not need to know who is connected. You could also build your own topic that you send out a request for all clients to respond to and look for their posts. I have not done this myself but Rossen (one of the commentors) is one of the main authors of the project so I believe him!

    希望这会有所帮助。请告诉我。

    Hopefully this helps. Let me know.

    这篇关于Spring Boot + Websocket(SockJS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆