spring-boot WebSocket 集成

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

配置类

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


    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        stompEndpointRegistry.addEndpoint(Constant.WEBSOCKETPATH).withSockJS();
    }


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

常量

//webSocket相关配置
//链接地址
public static final String WEBSOCKETPATHPERFIX = "/ws-push";
public static final String WEBSOCKETPATH = "/endpointWisely";
//消息代理路径
public static final 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";

对应service

@Service
public class WebSocketService {
    @Autowired
    private SimpMessagingTemplate template;

    /**
     * 广播
     * 发给所有在线用户
     *
     * @param msg
     */
    public void sendMsg(WiselyResponse msg) {
        template.convertAndSend(Constant.PRODUCERPATH, msg);
    }

    /**
     * 发送给指定用户
     * @param users  用户名List
     * @param msg  消息实体
     */
    public void sendUsers(List<String> users, WiselyResponse msg) {
        users.forEach(userName -> {
            template.convertAndSendToUser(userName, Constant.P2PPUSHPATH, msg);
        });
    }

    /**
     * 发送消息
     * @param userName  用户名
     * @param msg  消息实体
     */
    public void sendUsers(String userName, WiselyResponse msg) {
        template.convertAndSendToUser(userName, Constant.P2PPUSHPATH, msg);
    }

}

推送消息

//pc页面推送展现
webSocketService.sendUsers(newUser.getUsername(),new WiselyResponse(Constant.USER,"修改用户信息"));

前台

<!-- jQuery 2.2.3 -->
<script src="${pageContext.request.contextPath}/content/ui/global/jQuery/jquery.min.js"></script>
<!-- Bootstrap 3.3.6 -->
<script src="${pageContext.request.contextPath}/content/ui/global/bootstrap/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/content/plugins/stomp/sockjs.min.js"></script>
<script src="${pageContext.request.contextPath}/content/plugins/stomp/stomp.js"></script>

bod

<body  onload="connect();">
<script type="text/javascript">
    var stompClient = null;
    var userName = '${sessionScope.loginUser.username}';

    /**
     * 连接
     *
     * */
    function connect() {
        var socket = new SockJS('${ctx}/endpointWisely');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            console.log('Connected:' + frame);
            //4通过stompClient.subscribe()订阅服务器的目标是'/topic/getResponse'发送过来的地址,与@SendTo中的地址对应。
            stompClient.subscribe('/topic/getResponse', function (respnose) {
                showResponse(JSON.parse(respnose.body).responseMessage);
            });
            //4通过stompClient.subscribe()订阅服务器的目标是'/user/' + userId + '/msg'接收一对一的推送消息,其中userId由服务端传递过来,用于表示唯一的用户,通过此值将消息精确推送给一个用户
            stompClient.subscribe('/user/' + userName + '/msg', function (respnose) {
                //console.log("user");
                showResponse(JSON.parse(respnose.body).responseMessage);
            });
        });
    }
    /**
     * 断开连接
     */
    function disconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
    }
    //发送消息
    function sendName() {
        var name = "测试" + Math.random();
        //console.log('name:' + name);
        stompClient.send("/ws-push/welcomeMsg", {}, JSON.stringify({'name': name}));
    }
    function loginOut() {
        layer.confirm('确定要退出本系统吗?', function (index) {
            //window.open("${ctx}/logout");
            layer.close(index);
            window.location = "${ctx}/logout";
        });
    }
    /**
     * 右下角弹出消息
     * @param message
     */
    function showResponse(message) {
        //$("#prompt").attr("autoplay","autoplay");
        //边缘弹出
        layer.open({
            type: 1,
            offset: 'rb', //具体配置参考:offset参数项
            content: '<div style="padding: 20px 80px;">' +
            '<audio src="${ctxContent}/ui/music/prompt.mp3" hidden controls="controls" autoplay="autoplay">' +
            'Your browser does not support the audio element.' +
            '</audio>' + '安全小管家提醒您:来消息了,请注意查收。<br/>' + message + '</div>',
            btn: '关闭全部',
            btnAlign: 'c', //按钮居中
            shade: 0,//不显示遮罩
            yes: function () {
                layer.closeAll();
            }
        });
    }


</script>

猜你喜欢

转载自blog.csdn.net/qq_33842795/article/details/80227145