• springboot-websocket基础使用


    话不多说直接上代码关于介绍websocket百度一大堆 这里只作为个人学习笔记吧

    依赖添加

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

    穿件configer类

    package com.zly.ws.websocket.confige;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    
    /**
     * @Author zly
     * @Date 2018/11/6 11:22
     */
    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter(){
            return new ServerEndpointExporter();
        }
    }

    新建一个mywebsocket

    package com.zly.ws.websocket.mywebsocket;
    
    import com.zly.ws.websocket.entity.User;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    /**
     * @Author zly
     * @Date 2018/11/6 11:25
     */
    @ServerEndpoint(value = "/websocket")
    @Component
    public class MyWebSocket {
        public static int onlineCount=0;
        public static CopyOnWriteArraySet<MyWebSocket> sockets=new CopyOnWriteArraySet<>();
        public Session session;
        public static Logger logger=LoggerFactory.getLogger(MyWebSocket.class);
        @OnOpen
        public void onOpen(Session session){
           //User user = (User)request.getSession().getAttribute("user");
            this.session = session;
            sockets.add(this);     //加入set中
            addOnlineCount();           //在线数加1
            //System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
            logger.info("链接加入!当前在线人数为"+getOnlineCount());
            try {
                sendMessage(CommonConstant.CURRENT_WANGING_NUMBER.toString());
            } catch (IOException e) {
                logger.info("IO异常");
            }
        }
    
        @OnClose
        public void onClose() {
            sockets.remove(this);  //从set中删除
            subOnlineCount();           //在线数减1
            logger.info("有人退出了链接!在线人数是:"+getOnlineCount());
        }
    
        /**
         * 收到客户端消息后调用的方法
         *
         * @param message 客户端发送过来的消息*/
        @OnMessage
        public void onMessage(String message, Session session) {
          logger.info("客户端发来了消息"+message);
    
            //群发消息
            for (MyWebSocket item : sockets) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        /**
         * 发生错误时调用
         @OnError
         */
         public void onError(Session session, Throwable error) {
         logger.info("发生了错误");
         error.printStackTrace();
         }
    
    
         public void sendMessage(String message) throws IOException {
         this.session.getBasicRemote().sendText(message);
         //this.session.getAsyncRemote().sendText(message);
         }
    
    
         /**
          * 群发自定义消息
          * */
        public static void sendInfo(String message) throws IOException {
            for (MyWebSocket item : sockets) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    continue;
                }
            }
        }
    
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount() {
            MyWebSocket.onlineCount++;
        }
    
        public static synchronized void subOnlineCount() {
            MyWebSocket.onlineCount--;
        }
    }

    最后前端页面

    这里是用的是thymleaf

    <!DOCTYPE HTML>
    <html>
    <head>
        <title>My WebSocket</title>
    </head>
    
    <body>
    Welcome {user.nickname}<br/>
    <input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
    <div id="message">
    </div>
    </body>
    
    <script type="text/javascript">
        var websocket = null;
    
        //判断当前浏览器是否支持WebSocket
        if('WebSocket' in window){
            websocket = new WebSocket("ws://localhost:8080/websocket");
        }
        else{
            alert('Not support websocket')
        }
    
        //连接发生错误的回调方法
        websocket.onerror = function(){
            setMessageInnerHTML("error");
        };
    
        //连接成功建立的回调方法
        websocket.onopen = function(event){
            setMessageInnerHTML("open");
        }
    
        //接收到消息的回调方法
        websocket.onmessage = function(event){
            setMessageInnerHTML(event.data);
        }
    
        //连接关闭的回调方法
        websocket.onclose = function(){
            setMessageInnerHTML("close");
        }
    
        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function(){
            websocket.close();
        }
    
        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML){
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }
    
        //关闭连接
        function closeWebSocket(){
            websocket.close();
        }
    
        //发送消息
        function send(){
            var message = document.getElementById('text').value;
            websocket.send(message);
        }
    </script>
    </html>

    启动项目访问访问页面

  • 相关阅读:
    从零到有模拟实现一个Set类
    node+express+mysql 实现登陆注册
    从路由原理出发,深入阅读理解react-router 4.0的源码
    linux rsyncserver文件同步
    为什么说Python是一门动态语言--Python的魅力
    python基础教程_学习笔记11:魔法方法、属性和迭代器
    list,set,map,数组间的相互转换
    TCP/IP协议族
    宿舍更换的新淋浴喷头"水温vs旋钮角度"关系的研究(曲线)
    单元測试中 Right-BICEP 和 CORRECT
  • 原文地址:https://www.cnblogs.com/blackCatFish/p/9917067.html
Copyright © 2020-2023  润新知