• SpringBoot中使用Websocket进行消息推送



    WebsocketConfig.java

    
    @Configuration
    public class WebSocketConfig {
        @Bean
        public ServerEndpointExporter serverEndpointExporter() {
            return new ServerEndpointExporter();
        }
    }
    
    


    WebsocketServer.java

    
    @Log4j
    @Component
    @ServerEndpoint("/websocket/{id}")
    public class WebsocketServer {
        private static Map<String, Session> connections = new HashMap<>();
        private Session session;
        @OnOpen
        public void onOpen(Session session, @PathParam("id") String id) {
            this.session = session;
            connections.put(id, session);
        }
        @OnMessage
        public void onMessage(String text){
            log.info("WebSocket连接数:" + connections.size());
            String[] s = text.split("]#!]");
            Session ses = connections.get(s[0]);
            try {
                ses.getBasicRemote().sendText(s[1]);
            } catch (IOException e) {
                MythException.recode("websocket服务器异常:"+e.getMessage(), e, WebsocketServer.class);
            }
        }
        @OnError
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
            log.error(throwable.getMessage());
        }
        @OnClose
        public void onClosing() throws IOException {
            connections.remove(session);
            session.close();
        }
    }
    
    


    WebsocketClient.java

    
    @Component
    @Log4j
    @ClientEndpoint
    public class WebSocketClient {
    
        private Session session;
    
        @OnOpen
        public void onOpen(Session session) {
            this.session = session;
        }
    
        @OnMessage
        public void onMessage(String text) throws IOException {
            session.getBasicRemote().sendText(text);
        }
    
        @OnError
        public void onError(Throwable throwable) {
            log.error(throwable.getMessage());
        }
    
        @OnClose
        public void onClosing() throws IOException {
    //        log.info("连接关闭");
            session.close();
        }
    
        public void sendMessage(String toId, String text) throws IOException {
            text = toId + "]#!]" + text;
    //        log.info(text);
            onMessage(text);
        }
    
        public static WebSocketClient connect(String url) throws Exception {
            WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();
            WebSocketClient client = new WebSocketClient();
            wsc.connectToServer(client, new URI(url));
            return client;
        }
    
    }
    
    


    Use.java

    
     WebSocketClient client;
        try {
            client = WebSocketClient.connect("ws://wx.jjyouhuigo.com/websocket/system");
            // 发送消息, id 为接受者id, text为发送的信息
            client.sendMessage(id, System.currentTimeMillis()+" 文件导入有错误,请重新配置后导入");
            // 关闭连接
            client.onClosing();
        } catch (Exception e) {
            e.printStackTrace();
        }
    
    


    View.js

    
    var ws = new WebSocket("ws://127.0.0.1/websocket/" + id);
    ws.onopen = function () {
        console.log("open");
    };
    ws.onmessage = function (evt) {
        console.log(evt.data)
    };
    ws.onclose = function (evt) {
        console.log("close");
    };
    ws.onerror = function (evt) {
        console.log("error");
    };
    
    
  • 相关阅读:
    未能从程序集 C:Program Files (x86)MSBuild14.0inMicrosoft.Data.Entity.Build.Tasks.dll 加载任务“EntityClean”
    asp.net mvc 4 项目升级到 asp.net mvc5
    SQL Server查看所有表大小,所占空间
    0x80072f8a未指定的错误
    vs2012 aps.net4.0/4.5尚未在web服务器上注册
    vsphere 出现“在主机的当前连接状况下不允许执行该操作”
    sql server 发布时提示'dbo.sysmergepublications'无效的解决办法
    sql server更改机器名后更改数据库机器名
    Ajax向后台传入File类型参数
    上传下载Azure Blob里的Excel文件。
  • 原文地址:https://www.cnblogs.com/datiangou/p/10222384.html
Copyright © 2020-2023  润新知