• SpringMVC集成WebSocket【使用原生API】


    使用JSR 356 API编写WebSocket应用,借鉴地址:https://www.baeldung.com/java-websockets

    1.添加依赖

        <dependency>
          <groupId>javax.websocket</groupId>
          <artifactId>javax.websocket-api</artifactId>
          <version>1.1</version>
        </dependency>

    2.编写一些配置【可忽略】

    package cn.coreqi.servletsocketdemo.config;
    
    import javax.servlet.http.HttpSession;
    import javax.websocket.HandshakeResponse;
    import javax.websocket.server.HandshakeRequest;
    import javax.websocket.server.ServerEndpointConfig;
    
    /**
     * 获取session所在的 httpSession
     */
    public class GetHttpSessionConfigurator extends ServerEndpointConfig.Configurator {
        @Override
        public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
            HttpSession httpSession = (HttpSession) request.getHttpSession();
            sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
        }
    }

    3.编写服务端端点

    package cn.coreqi.servletsocketdemo.websocket;
    
    import cn.coreqi.servletsocketdemo.config.GetHttpSessionConfigurator;
    import cn.coreqi.servletsocketdemo.model.DefaultResultModel;
    import com.alibaba.fastjson.JSONObject;
    import org.springframework.stereotype.Component;
    
    import javax.websocket.*;
    import javax.websocket.server.PathParam;
    import javax.websocket.server.ServerEndpoint;
    import java.util.HashMap;
    import java.util.Map;
    
    @Component
    @ServerEndpoint(value = "/websocket/{projectId}",configurator = GetHttpSessionConfigurator.class)
    public class WebSocketTest {
    
        // 保存所有的用户session
        private static Map<String, Session> SESSION_MAP = new HashMap<>();
    
        @OnOpen
        public void onOpen(Session session, @PathParam(value="projectId")String projectId) {
            DefaultResultModel model = new DefaultResultModel();
            model.setNow(System.currentTimeMillis());
            model.setData(projectId);
            model.setMsg("onOpen");
            session.getAsyncRemote().sendText(JSONObject.toJSONString(model));
        }
    
        @OnError
        public void onError(Throwable t) {
            System.err.println("WebSocket出错了");
            t.printStackTrace();
        }
    
        @OnClose
        public void onClose() {
        }
    
        @OnMessage
        public void onMessage(Session session,String message) {
            DefaultResultModel model = new DefaultResultModel();
            model.setNow(System.currentTimeMillis());
            model.setData(message);
            model.setMsg("onMessage");
            session.getAsyncRemote().sendText(JSONObject.toJSONString(model));
        }
    
    }

    4.前端页面【需要浏览器原生支持WebSocket】

      <script type="text/javascript">
        var div = document.getElementById('div');
        var prefix = "ws://localhost:8080/";
        var websocketUrl = prefix + 'websocket/7777';
        var socket = new WebSocket(websocketUrl);
        socket.onopen = function(event){
          console.log(event);
          socket.send('websocket client connect test');
        }
    
        socket.onclose = function(event){
          console.log(event);
        }
    
        socket.onerror = function(event){
          console.log(event);
        }
    
        socket.onmessage = function(event){
          console.log(event)
          div.innerHTML += ('接受到服务器消息:' + event.data);
        }
      </script>
  • 相关阅读:
    去除网页图片缝隙
    只有定位的盒子有z-index
    clearfix
    2018CSS特效集锦牛逼
    c#spinLock使用
    redis 五种数据结构详解(string,list,set,zset,hash)
    C# StackExchange.Redis 用法总结
    Markdown 编辑器
    C# Task任务详解及其使用方式
    MongoDB学习笔记——MongoDB 连接配置
  • 原文地址:https://www.cnblogs.com/fanqisoft/p/16125277.html
Copyright © 2020-2023  润新知