Spring 基于websocket 的推送接收消息

  • Post author:
  • Post category:其他




Spring 基于websocket 的推送接收消息



创建后端服务类,通过ServerEndPoint注解将类注解为服务端

package com.erdp.service;

import javax.mail.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndPoint(value = "/websocket/message/{userId}")
public class MessageServer {
    private static Map<String,MessageServer> clients = new ConcurrentHashMap<>();
    private Session session;
    private String userId;
    private static Map<String, List<String>> userAndSessions = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(@PathParam("userId")String userId,Session session){
        this.session = session;
        this.userId = userId;
        String sessionId = session.getId();
        clients.put(sessionId,this);
        List<String> list = userAndSessions.get(userId);
        if(list == null){
            list = new ArrayList<>();
        }
        list.add(sessionId);
        userAndSessions.put(userId,list);
    }
    @OnClose
    public void onClose(){
        clients.remove(session.getId());
        List<String> list = userAndSessions.get(userId);
        list.remove(session.getId());
        if(list.size() == 0){
            userAndSessions.remove(userId);
        }
    }
    @OnError
    public void OnError(Session session,Throwable t){
        t.printStackTrace();
    }
    @OnMessage
    public void OnMessage(String userName,String text){
        sendMessageTo(userName,text);
    }
    public static void sendMessageTo(String userName,String text){
        List<String>list = userAndSessions.get(userName);
        if(list == null){
            return;
        }for(String sessionId:list){
            MessageServer messageServer = clients.get(sessionId);
            sendMessage(messageServer,text);
        }
    }

    private static void sendMessage(MessageServer messageServer,String message){
        if (messageServer != null){
            messageServer.session.getAsyncRemote().sendText(message);
        }
    }
}



前端客户端调用

layui.use(['jquery','layui'],function(){
   var layer  = layui.layer;
   $(function () {
        var websocket = null;
        if('WebSocket' in window){
            websocket = new WebSocket('/websocket/message/{userId}')
            websocket.onmessage = function(e) {
                o = false;
                if(timeout){
                    loginOut();
                }
            }
            websocket.onclose = function() {
                loginOut();
            }
            websocket.onmessage = function(ev) {
                var data = ev.data.replace(new RegExp("\n","gm"),"")
                var activeInfo = JSON.parse(data);
            }
        }
    })
});



调用方式

package com.erdp.service;
public class PasuController {
    MessageServer.sendMessageTo("userId","具体发送的消息内容");
}



版权声明:本文为qq_35253422原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。