zoukankan      html  css  js  c++  java
  • Spring Boot WebSocket

    简介:WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端。

    Config:

    Controller:


    完整代码如下:

    Html:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8" />
        <title>Spring Boot WebSocket</title>
    
    </head>
    <body onload="disconnect()">
    <noscript><h2 style="color: #ff0000">浏览器不支持websocket</h2></noscript>
    <div>
        <div>
            <button id="connect" onclick="connect();">连接</button>
            <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
        </div>
        <div id="conversationDiv">
            <label>输入你的名字</label><input type="text" id="msg" />
            <button id="sendName" onclick="sendMsg();">发送</button>
            <p id="response"></p>
        </div>
    </div>
    <script src="/js/jquery-2.1.0.min.js"></script>
    <script src="/js/stomp.min.js"></script>
    <script src="/js/sockjs-0.3.4.min.js"></script>
    <script type="text/javascript">
        var stompClient = null;
    
        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('/ruan');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('开始进行连接Connected: ' + frame);
                stompClient.subscribe('/resp', function(respnose){
                    showResponse(respnose.body);
                });
            });
        }
    
    
        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("Disconnected");
        }
    
        function sendMsg() {
            var msg = $('#msg').val();
            stompClient.send("/msg", {}, msg);//5
        }
    
        function showResponse(message) {
            var response = $("#response");
            response.html(message);
        }
    </script>
    </body>
    </html>

     Config:

    package com.example.websocketdemo.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.messaging.simp.config.MessageBrokerRegistry;
    import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
    import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
    import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
    
    /**
     * @author Ruan
     * @date 2018/4/11 21:13
     * @EnableWebSocketMessageBroker 开启使用STOMP协议来传输基于代理(MessageBroker)的消息,
     * 让controller支持@MessageMapping注解,和requestMapping类似
     */
    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            //注册Stomp节点,并使用SockJS协议
            registry.addEndpoint("/ruan").withSockJS();
        }
    
        @Override
        public void configureMessageBroker(MessageBrokerRegistry registry) {
            //用来定义返回的规范.返回url以 /resp 开始
            registry.enableSimpleBroker("/resp");
        }
    }

     Contoller:

    package com.example.websocketdemo.controller;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.messaging.handler.annotation.MessageMapping;
    import org.springframework.messaging.handler.annotation.SendTo;
    import org.springframework.stereotype.Controller;
    
    /**
     * @author Ruan
     * @date 2018/4/11 21:15
     */
    @Controller
    @Slf4j
    public class WsController {
        /**
         * 接收来自浏览器通过/msg 这个api发送过来的消息
         * @MessageMapping 浏览器通过这个注解里面的api访问改方法
         * @SendTo 返回给浏览器的地址
         * @param msg 消息内容
         * @return
         */
        @MessageMapping("/msg")
        @SendTo("/resp")
        public String receive(String msg) {
            StringBuilder sbReceiver = new StringBuilder("服务器返回消息: ");
            sbReceiver.append(msg);
            log.info(sbReceiver.toString());
            return sbReceiver.toString();
        }
    }
  • 相关阅读:
    笔记2-斐波那契数列
    笔记1-排序
    C++ 顶层const和底层const ?
    C++指针常量与常量指针的区别?
    C++指针和引用的区别?
    函数指针, 指针函数?
    手机横竖屏问题
    Swift
    Swift 渐变色
    Swift guard 关键字
  • 原文地址:https://www.cnblogs.com/cearnach/p/8798875.html
Copyright © 2011-2022 走看看