美文网首页
springBoot socket

springBoot socket

作者: dwwl | 来源:发表于2019-11-04 15:02 被阅读0次

    做个SpringBoot Socket使用的简单记录

    功能:后台实时向前台发送提醒信息

     <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-websocket</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
            <dependency>
                <groupId>net.sf.json-lib</groupId>
                <artifactId>json-lib</artifactId>
                <version>2.2.3</version>
                <classifier>jdk15</classifier><!-- jdk版本 -->
            </dependency>
    
        </dependencies>
    
    @Component
    @ServerEndpoint("/msg/{userID}")
    public class MsgSocket {
    
        private static final Logger logger = LoggerFactory.getLogger(MsgSocket.class);
        private static Map<String, Session> clients = new ConcurrentHashMap<>();
    
        @OnOpen
        public void open(@PathParam("userID")String userID,Session session) {
            clients.put(userID, session);
            logger.info("userID:{},session:{}",userID,session.getAsyncRemote());
        }
    
        @OnMessage
        public void onMessage(String message) throws IOException {
            JSONObject jsonTo = JSONObject.fromObject(message);
            String msg = (String) jsonTo.get("message");
            String userID = (String) jsonTo.get("userID");
    
            sendMessageTo(msg,userID);
    
        }
    
        private void sendMessageTo(String message, String userID) throws IOException {
            Session session = clients.get(userID);
    
            if (session == null) {
                return;
            }
    
            session.getAsyncRemote().sendText(message);
        }
    
        @OnError
        public void onError(Session session, Throwable error) {
            error.printStackTrace();
        }
    
    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }
    
    @RestController
    public class TestController {
    
        @GetMapping("/test")
        public String test() throws IOException {
    
            MsgSocket msgSocket = new MsgSocket();
            JSONObject jo = new JSONObject();
            jo.put("message", "这是后台返回的消息!");
            jo.put("userID","huang");
            msgSocket.onMessage(jo.toString());
    
            return "success";
        }
    }
    

    用一个简单页面做测试

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <script>
        var websocket = null;
    
        var host = document.location.host;
    
        var username = "huang"; // 获得当前登录人员的userName
    
        // alert(username)
    
        //判断当前浏览器是否支持WebSocket
    
        if ('WebSocket' in window) {
    
            alert("浏览器支持Websocket"+host)
    
            websocket = new WebSocket('ws://' + 'localhost:8080' + '/msg/' + username);
            alert('ws://' + 'localhost:8080' + '/msg/' + username)
    
        } else {
    
            alert('当前浏览器 Not support websocket')
    
        }
    
    
        //连接发生错误的回调方法
    
        websocket.onerror = function (e) {
    
            alert(e)
    
            alert("WebSocket连接发生错误")
    
            setMessageInnerHTML("WebSocket连接发生错误");
    
        };
    
    
        //连接成功建立的回调方法
    
        websocket.onopen = function () {
    
            alert("WebSocket连接成功")
    
            setMessageInnerHTML("WebSocket连接成功");
    
        }
    
    
        //接收到消息的回调方法
    
        websocket.onmessage = function (event) {
    
            alert("接收到消息的回调方法")
    
            alert("这是后台推送的消息:" + event.data);
    
            websocket.close();
    
            alert("webSocket已关闭!")
    
        }
    
    
        //连接关闭的回调方法
    
        websocket.onclose = function () {
    
            setMessageInnerHTML("WebSocket连接关闭");
    
        }
    
    
        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    
        window.onbeforeunload = function () {
    
            closeWebSocket();
    
        }
    
    
        //关闭WebSocket连接
    
        function closeWebSocket() {
    
            websocket.close();
    
        }
    
    
        //将消息显示在网页上
    
        function setMessageInnerHTML(innerHTML) {
    
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
    
        }
    </script>
    <body>
    
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:springBoot socket

          本文链接:https://www.haomeiwen.com/subject/szubvctx.html