zoukankan      html  css  js  c++  java
  • sprint boot websocket 服务端+html5 示例测试

    包依赖:

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


    配置类 WebSocketConfig.java

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.WebSocketHandler;
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
    
    
    import javax.websocket.server.ServerEndpointConfig;
    
    @Configuration
    public class WebSocketConfig extends ServerEndpointConfig.Configurator {
    
        public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
            registry.addHandler(myHandler(), "")
                    .setAllowedOrigins("*");
        }
    
        public WebSocketHandler myHandler() {
            return new AlarmWebSocket();
        }
    
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            ServerEndpointExporter serverEndpointExporter = new ServerEndpointExporter();
            return serverEndpointExporter;
        }
    }

    WebSocketTest.java

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Component;
    import org.springframework.web.socket.handler.TextWebSocketHandler;
    
    import javax.websocket.*;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    @ServerEndpoint(value = "/websocketOne",configurator = WebSocketConfig.class)
    @Component
    public class AlarmWebSocket extends TextWebSocketHandler {
        public final static Logger logger = LoggerFactory.getLogger(AlarmWebSocket.class);
    
        private static int onlineCount = 0;
    
        //用来存放每个客户端对应的MyWebSocket对象。
        private static CopyOnWriteArraySet<AlarmWebSocket> webSocketMap = new CopyOnWriteArraySet<AlarmWebSocket>();
        private Session session;
    
    
        @OnOpen
        public void onOpen(Session session) throws IOException {
            this.session = session;
            webSocketMap.add(this);
            addOnlineCount();
    
            this.sendMessage(""); // TODO: 建立连接推送到前端的数据
            logger.info("create new webSocket connect!now WebSocket Client number is " + getOnlineCount());
        }
    
    
        @OnClose
        public void onClose(){
    
            webSocketMap.remove(this);
            subOnlineCount();
            System.out.println("close one webSocket connect!now WebSocket Client is " + getOnlineCount());
    
        }
    
        /**
         * 收到客户端消息后调用的方法
         * @param message 客户端发送过来的消息
         * @param session 可选的参数
         */
        @OnMessage
        public void onMessage(String message, Session session) throws IOException {
            System.out.println(7777);
    
            //发送的用户号就是session.hashcode(),可以再加个map继续映射
           /* int pos=message.indexOf("#*#*");
            String realmessage=message.substring(0,pos);
            String realuser=message.substring(pos+4,message.length());*/
            System.out.println("来自客户端的消息:" + message);
            //
           /* WebSocketTest item=webSocketMap.get(realuser);
            item.sendMessage(realmessage);*/
            sendMessage(message);
    
        }
    
        /**
         * 群发自定义消息
         */
        public static void sendInfo(String message) {
            System.out.println(66666);
    
            //log.info(message);
    
    
            for (AlarmWebSocket item : webSocketMap) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    //log.error("向客户端发送数据失败!", e);
                    //continue;
                }
            }
        }
    
    
        /**
         * 发生错误时调用
         * @param session
         * @param error
         */
        @OnError
        public void onError(Session session, Throwable error){
            System.out.println("发生错误");
            error.printStackTrace();
        }
    
        /**
         * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
         * @param message
         * @throws IOException
         */
        //给客户端传递消息
        public void sendMessage(String message) throws IOException{
    
            this.session.getBasicRemote().sendText(message);
            //this.session.getAsyncRemote().sendText(message);
        }
    
    
        public static synchronized int getOnlineCount() {
            return onlineCount;
        }
    
        public static synchronized void addOnlineCount() {
            AlarmWebSocket.onlineCount++;
        }
    
        public static synchronized void subOnlineCount() {
            AlarmWebSocket.onlineCount--;
        }
    
    
    }

    html

    <!DOCTYPE html>
    
    <html>
    
    <head>
    
        <meta charset="UTF-8">
    
        <title>RevealWebSocket</title>
    
     
    
        <script src="js/vue.js"></script>
    
    </head>
    
    <body>
    
    接受数据<br/><br/>
    
        <div id="ws">
    
        <input id="text" type="text"/>
    
        <button onclick="sendMsg()">Send</button>
    
        <button onclick="closeWS()" :disabled="!opened">Close</button>
    
        <button onclick="openWS()"  :disabled="opened">Open</button>
    
        <div v-html="msg"></div>
    
        </div>
    
    </body>
    
     
    
    <script type="text/javascript">
    
        var websocket = null;
    
     
    
        var wsVue = new Vue({
    
            el: '#ws',
    
            data: {
    
                msg: "welcome to my websocket...<br/>",
    
                opened: false
    
            },
    
            mounted: function(){
    
                initWs();
    
            }
    
        });
    
     
    
        function initWs() {
    
            //check if your browser supports WebSocket
    
            if ('WebSocket' in window) {
    
                //websocket = new WebSocket("ws://124.207.211.211:85/monitor/monitor/socket");
                websocket = new WebSocket("ws://localhost:9001/websocketOne");
                //websocket = new WebSocket("ws://192.168.1.53:9100/monitor/websocketOne");
            }
    
            else {
    
                alert('Sorry, websocket not supported by your browser.')
    
            }
    
     
    
            //Error callback
    
            websocket.onerror = function () {
    
                setMessageContent("error!");
    
                wsVue.opened = false;
    
            };
    
     
    
            //socket opened callback
    
            websocket.onopen = function (event) {
    
                setMessageContent("websocket opened");
    
                wsVue.opened = true;
    
            }
    
     
    
            //message received callback
    
            websocket.onmessage = function (event) {
    
                setMessageContent(event.data);
    
            }
    
     
    
            //socket closed callback
    
            websocket.onclose = function () {
    
                setMessageContent("websocket closed");
    
                wsVue.opened = false;
    
            }
    
     
    
            //when browser window closed, close the socket, to prevent server exception
    
            window.onbeforeunload = function () {
    
                websocket.close();
    
            }
    
        }
    
     
    
        //update message to vue and then in div
    
        function setMessageContent(content) {
    
            wsVue.msg = content;
    
        }
    
     
    
        //click to close the websocket
    
        function closeWS() {
    
            websocket.close();
    
            wsVue.opened = false;
    
        }
    
     
    
        //click to open the websocket
    
        function openWS() {
    
            initWs();
    
        }
    
     
    
        //click to send message
    
        function sendMsg() {
    
            var message = document.getElementById('text').value;
    
            websocket.send(message);
    
        }
    
    </script>
    
    </body>
    
    </html>
  • 相关阅读:
    心慌慌
    辛苦了
    [转]家庭长寿秘方:夫妻关系之守则。
    无题
    浮躁
    [转]樱木花道9大缺点
    一票难求
    Excel录入数据,自动记录当前时间点
    Excel数据透视表基本使用
    linux下tomcat7虚拟目录配置
  • 原文地址:https://www.cnblogs.com/zhzhlong/p/11171775.html
Copyright © 2011-2022 走看看