栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring:向websocket客户端发送消息

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring:向websocket客户端发送消息

好的,我想我明白了,对于需要它的每个人,这是答案:

首先,您需要将WS依赖项添加到pom.xml中

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-messaging</artifactId></dependency>

创建一个WS端点

@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {    @Override    public void registerStompEndpoints(StompEndpointRegistry registry) {        // the endpoint for websocket connections        registry.addEndpoint("/stomp").withSockJS();    }    @Override    public void configureMessageBroker(MessageBrokerRegistry config) {        config.enableSimpleBroker("/");        // use the /app prefix for others        config.setApplicationDestinationPrefixes("/app");    }}

注意:我使用的是STOMP,因此客户端应该这样连接

<script type="text/javascript">    $(document).ready(function() {        var messageList = $("#messages");        // defined a connection to a new socket endpoint        var socket = new SockJS('/stomp');        var stompClient = Stomp.over(socket);        stompClient.connect({ }, function(frame) { // subscribe to the /topic/message endpoint stompClient.subscribe("/room.2", function(data) {     var message = data.body;     messageList.append("<li>" + message + "</li>"); });        });    });</script>

然后,您可以简单地将ws Messenger连接到组件上

@Autowiredprivate SimpMessagingTemplate webSocket;

并发送消息与

webSocket.convertAndSend(channel, new String(message.getBody()));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/615579.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号