springboot整合webSocket的使用

1 配置config

package com.test.domi.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
// @EnableWebSocketMessageBroker注解用于开启使用STOMP协议来传输基于代理(MessageBroker)的消息,这时候控制器(controller)
// 开始支持@MessageMapping,就像是使用@requestMapping一样。
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        //注册一个Stomp的节点(endpoint),并指定使用SockJS协议。
        stompEndpointRegistry.addEndpoint("/endpointAric").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //服务端发送消息给客户端的域,多个用逗号隔开
        registry.enableSimpleBroker("/topic");
        //定义一对一推送的时候前缀
        //registry.setUserDestinationPrefix("/user");
        //定义websoket前缀
        //registry.setApplicationDestinationPrefixes("/ws-push");
    }

    /*
    //webSocket相关配置
    //链接地址
    public static String WEBSOCKETPATHPERFIX = "/ws-push";
    public static String WEBSOCKETPATH = "/endpointWisely";
    //消息代理路径
    public static String WEBSOCKETBROADCASTPATH = "/topic";
    //前端发送给服务端请求地址
    public static final String FORETOSERVERPATH = "/welcome";
    //服务端生产地址,客户端订阅此地址以接收服务端生产的消息
    public static final String PRODUCERPATH = "/topic/getResponse";
    //点对点消息推送地址前缀
    public static final String P2PPUSHBASEPATH = "/user";
    //点对点消息推送地址后缀,最后的地址为/user/用户识别码/msg
    public static final String P2PPUSHPATH = "/msg";
    **/
}

  

2 controller

package com.test.domi.controller;

import com.google.common.collect.Lists;
import com.test.domi.service.impl.WebSocketService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;
import java.util.List;

@Controller
public class WsController {

    @Resource
    private SimpMessagingTemplate template;

    @MessageMapping("/welcome")//@MessageMapping和@RequestMapping功能类似,用于设置URL映射地址,浏览器向服务器发起请求,需要通过该地址。
    public void say(String message) throws Exception {
        template.convertAndSend("/topic/getResponse", message);
    }

}

 

3 前台页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Spring Boot+WebSocket+DVD</title>
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<noscript><h2 style="color: #ff0000">NOT SUPPORT websocket</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">connect</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">close</button>
    </div>
    <div id="conversationDiv">
        <label>your name</label><input type="text" id="name" />
        <button id="sendName" onclick="sendName();">send</button>
        <p id="response"></p>
        <p id="response1"></p>
    </div>
    <div id="output"></div>
</div>
</body>
<script th:inline="javascript">
    var stompClient = null;
    //点对点模式,用用户ID区分不同的用户
   // var userId = [[${userId}]];

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $('#response').html();
    }

    function connect() {
        var socket = new SockJS('/endpointAric');
        stompClient = Stomp.over(socket);
        stompClient.connect('guest','guest', function(frame) {
            stompClient.subscribe('/topic/getResponse', handleNotification);
        });
        function handleNotification(message) {
            $("#output").append("<b>Received: "+message.body+"</b><br/>")
        }
    }


    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {
        var name = $('#name').val();
        stompClient.send("/welcome", {}, JSON.stringify({ 'name': name }));
    }

    function showResponse(message) {
        var response = $("#response");
        response.html(message);
    }
</script>
</html>

  

猜你喜欢

转载自www.cnblogs.com/domi22/p/9460299.html