H5+springboot WebSocket的使用

引言:要实现的是提供二维码扫码成功后,推送支付成功的消息。
websocket+map存储websocket的Session,键为userId

前端代码:
// 如果验证成功,则新建一个websocket连接
if ("WebSocket" in window) {
this.websocket = new WebSocket("ws://localhost:8088/jeecg-boot/websocket/"+this.user.userId);
this.initWebSocket();
} else {
Toast("当前浏览器 Not support websocket");
}

initWebSocket () {
// 连接错误
this.websocket.onerror = this.setErrorMessage;
// 连接成功
this.websocket.onopen = this.setOnopenMessage;
// 收到消息的回调
this.websocket.onmessage = this.setOnmessageMessage;
// 连接关闭的回调
this.websocket.onclose = this.setOncloseMessage;
// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = this.onbeforeunload;
},
setErrorMessage () {
console.log("WebSocket连接发生错误 状态码:" + this.websocket.readyState);
},
setOnopenMessage () {
console.log("WebSocket连接成功 状态码:" + this.websocket.readyState);
},
setOnmessageMessage (event) {
// 根据服务器推送的消息做自己的业务处理
console.log("服务端返回:" + event.data);
if (event.data == "true") {
this.skSuccessShow = false;
this.ewmShow = true;
}
this.skSuccess = "";
},
setOncloseMessage () {
console.log("WebSocket连接关闭 状态码:" + this.websocket.readyState);
},
onbeforeunload () {
this.closeWebSocket();
},
closeWebSocket () {
this.websocket.close();
},

后端代码:
@Component
@ServerEndpoint("/websocket/{userName}")
//此注解相当于设置访问URL
public class WebSocket {

private final static Logger logger=LoggerFactory.getLogger(WebSocket.class);
private Session session;
private static CopyOnWriteArraySet webSockets =new CopyOnWriteArraySet<>();
private static Map sessionPool = new HashMap();

@OnOpen
public void onOpen(Session session, @PathParam(value="userName")String userName) {
    this.session = session;
    webSockets.add(this);
    sessionPool.put(userName, session);
    logger.info(userName+"【websocket消息】有新的连接,总数为:"+webSockets.size());
}

@OnClose
public void onClose() {
    webSockets.remove(this);
    logger.info("【websocket消息】连接断开,总数为:"+webSockets.size());
    logger.info("sessionPool的数量"+sessionPool.size());
}

@OnMessage
public void onMessage(String message) {
    System.out.println("【websocket消息】收到客户端消息:"+message);
}

// 此为广播消息
public void sendAllMessage(String message) {
    for(WebSocket webSocket : webSockets) {
        logger.info("【websocket消息】广播消息:"+message);
        try {
            webSocket.session.getAsyncRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// 此为单点消息
public void sendOneMessage(String userName, String message) {
    logger.info("【websocket消息】单点消息:"+message);
    Session session = sessionPool.get(userName);
    if (session != null) {
        try {
            session.getAsyncRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

}

我这只是简单的进行交互,所以用的是map来存储,当然数据量多的话可以选择使用redis等

你可能感兴趣的:(H5+springboot WebSocket的使用)