springboot与vue 集成 websocket方法

 Java代码:


import com.alibaba.fastjson.JSON;
import com.wpg.common.entity.ticket.TicketMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

/**
 * @author zhangzg
 * @ClassName: TicketWebSocket
 * @Description: 用来推送工单消息
 * @date 2018/8/16 10:55
 */
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class TicketWebSocket {

    //用来存放当前连接的session
    private Session session;
    //key为userId,value为Set
    private static Map> sessionPool = new HashMap>();
    //key为Session的id,value为userId
    private static Map sessionIds = new HashMap();

    /**
     * @Description: 用户连接时触发,将userId与session存进map,session存进Set
     * @param: [session, userId]
     * @return: void
     * @auther: zhangzg
     * @date: 2018/8/17 9:22
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        this.session = session;
        Set sessions = new HashSet();
        if (sessionPool.get(userId) != null) {
            sessions = sessionPool.get(userId);
        }
        sessions.add(session);
        sessionPool.put(userId, sessions);
        sessionIds.put(session.getId(), userId);
        log.debug("user:" + userId + "session:" + session.getId() + "连接成功");
    }

    /**
     * @Description: 收到消息时触发
     * @param: [message]
     * @return: void
     * @auther: zhangzg
     * @date: 2018/8/17 9:23
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("当前发送人sessionid为" + session.getId() + "内容:" + message);
//        System.out.println("当前发送人sessionid为" + session.getId() + "标题:" + message.getTitle()+"内容:"+message.getContent());
    }

    /**
     * @Description: 连接关闭时触发,从map中移除session与userId
     * @param: []
     * @return: void
     * @auther: zhangzg
     * @date: 2018/8/17 9:24
     */
    @OnClose
    public void onClose() {
        log.debug("sessionId为" + session.getId() + "的关闭");
        //从中取出userId
        String userId = sessionIds.get(session.getId());
        //根据userId找到对应Set,再从Set中移除该Session
        Set sessions = sessionPool.get(userId);
        if (sessions != null) {
            sessions.remove(session);
        }
        //覆盖原来的sessionPool中的数据
        sessionPool.put(userId, sessions);
        sessionIds.remove(session.getId());
    }

    /**
     * 发生错误时触发
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("webSocket发生错误");
        error.printStackTrace();
        log.debug("sessionId为" + session.getId() + "的webSocket关闭");
        //从中取出userId
        String userId = sessionIds.get(session.getId());
        //根据userId找到对应Set,再从Set中移除该Session
        Set sessions = sessionPool.get(userId);
        if (sessions != null) {
            sessions.remove(session);
        }
        //覆盖原来的sessionPool中的数据
        sessionPool.put(userId, sessions);
        sessionIds.remove(session.getId());
    }

    /**
     * @Description: 发送消息的方法,若用户不在线则不发送
     * @param: [message, userId]
     * @return: void
     * @auther: zhangzg
     * @date: 2018/8/17 9:27
     */
    public static void sendMessage(TicketMessage message, String userId) {
        Set sessions = sessionPool.get(userId);
        if (sessions != null) {
            for (Session s : sessions) {
                try {
                    System.out.println(JSON.toJSON(message));
                    s.getBasicRemote().sendText(JSON.toJSON(message).toString());
                } catch (IOException e) {
                    log.error("IOException异常,发送信息失败");
                    e.printStackTrace();
                }
            }
        } else {
            log.debug("session中不存在userId为" + userId + "的用户");

        }
    }

    /**
     * @Description: 返回当前的在线用户数
     * @param: []
     * @return: int
     * @auther: zhangzg
     * @date: 2018/8/17 9:32
     */
    public static int getOnlineNum() {
        return sessionPool.size();
    }

    /**
     * @Description: 返回在线的所有用户的userId,返回结果以“,”隔开
     * @param: []
     * @return: java.lang.String
     * @auther: zhangzg
     * @date: 2018/8/17 9:34
     */
    public static String getOnlineUsers() {
        StringBuffer users = new StringBuffer();
        for (String key : sessionIds.keySet()) {
            users.append(sessionIds.get(key) + ",");
        }
        return users.toString();
    }

    /**
     * @Description: 给在线的所有用户推送msg
     * @param: [msg]
     * @return: void
     * @auther: zhangzg
     * @date: 2018/8/17 9:36
     */
    public static void sendAll(TicketMessage msg) {
        for (String key : sessionIds.keySet()) {
            sendMessage(msg, sessionIds.get(key));
        }
    }

    /**
     * @Description: 给persons当中的用户发送msg
     * @param: [msg, persons]
     * @return: void
     * @auther: zhangzg
     * @date: 2018/8/17 9:37
     */
    public static void SendMany(TicketMessage msg, Set persons) {
        for (String userId : persons) {
            sendMessage(msg, userId);
        }
    }

    /**
     * @Description: 判断用户是否在线
     * @param: [userId]
     * @return: boolean
     * @auther: zhangzg
     * @date: 2018/8/21 15:33
     */
    public static boolean isOnline(String userId) {

        if (sessionPool.get(userId) != null) {
            log.debug("userId" + userId + "在线");
            return true;
        }
        log.debug("userId" + userId + "不在线");
        return false;
    }

}

Vue代码:

只用了initWs()方法和心跳检测方法,其他的可以作为参考






 

你可能感兴趣的:(SpringBoot,Vue,Java)