1、导入websocket包
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
<version>2.2.13.RELEASEversion>
dependency>
2、配置类
package com.ruoyi.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、常量类
package com.ruoyi.websocket.constant;
public class WsConstant {
public static final String CARDINFO="cardInfo";
public static final String IMGINFO="imgInfo";
}
4、Websocket工具类,记录当前在线的链接对链接进行操作
package com.ruoyi.websocket.utils;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class WebsocketUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(WebsocketUtil.class);
private static final Map<String, Session> ONLINE_SESSION = new ConcurrentHashMap<>();
public static final String sessionKey = "deviceId";
public static void addSession(String userId, Session session) {
ONLINE_SESSION.putIfAbsent(userId, session);
}
public static void removeSession(String userId) {
ONLINE_SESSION.remove(userId);
}
public static void sendMessage(Session session, String message) {
if (session == null) {
return;
}
RemoteEndpoint.Async async = session.getAsyncRemote();
async.sendText(message);
}
public static void sendMessageForAll(String message) {
ONLINE_SESSION.forEach((sessionId, session) -> {
if (session.isOpen()) {
sendMessage(session, message);
}
});
}
public static void sendMessage(String sessionId, AjaxResult result) {
sendMessage(sessionId, JSON.toJSONString(result));
}
public static void sendMessage(String sessionId, String message) {
Session session = ONLINE_SESSION.get(sessionId);
if (session == null || !session.isOpen()) {
return;
}
sendMessage(session, message);
}
public static Session getSession(String sessionId) {
Session session = ONLINE_SESSION.get(sessionId);
return session;
}
public static String getParam(String key, Session session) {
Map map = session.getRequestParameterMap();
Object userId1 = map.get(key);
if (userId1 == null) {
return null;
}
String s = userId1.toString();
s = s.replaceAll("\\[", "").replaceAll("]", "");
if (!StringUtils.isEmpty(s)) {
return s;
}
return null;
}
}
package com.ruoyi.common.core.domain;
import java.util.HashMap;
import com.ruoyi.common.utils.StringUtils;
public class AjaxResult extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
public static final String CODE_TAG = "code";
public static final String MSG_TAG = "msg";
public static final String DATA_TAG = "data";
public enum Type
{
SUCCESS(0),
WARN(301),
ERROR(500);
private final int value;
Type(int value)
{
this.value = value;
}
public int value()
{
return this.value;
}
}
public AjaxResult()
{
}
public AjaxResult(Type type, String msg)
{
super.put(CODE_TAG, type.value);
super.put(MSG_TAG, msg);
}
public AjaxResult(Type type, String msg, Object data)
{
super.put(CODE_TAG, type.value);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
super.put(DATA_TAG, data);
}
}
@Override
public AjaxResult put(String key, Object value)
{
super.put(key, value);
return this;
}
public static AjaxResult success()
{
return AjaxResult.success("操作成功");
}
public static AjaxResult success(Object data)
{
return AjaxResult.success("操作成功", data);
}
public static AjaxResult success(String msg)
{
return AjaxResult.success(msg, null);
}
public static AjaxResult success(String msg, Object data)
{
return new AjaxResult(Type.SUCCESS, msg, data);
}
public static AjaxResult warn(String msg)
{
return AjaxResult.warn(msg, null);
}
public static AjaxResult warn(String msg, Object data)
{
return new AjaxResult(Type.WARN, msg, data);
}
public static AjaxResult error()
{
return AjaxResult.error("操作失败");
}
public static AjaxResult error(String msg)
{
return AjaxResult.error(msg, null);
}
public static AjaxResult error(String msg, Object data)
{
return new AjaxResult(Type.ERROR, msg, data);
}
}
5、控制类
package com.ruoyi.websocket.wscontroller;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.netty.manager.DeviceChannelContext;
import com.ruoyi.netty.netty.factory.ChannelFactory;
import com.ruoyi.websocket.utils.WebsocketUtil;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
@Component
@ServerEndpoint(value = "/verifyDevice")
public class FaceVerifyController {
@OnOpen
public void onOpen(Session session) {
String deviceId = WebsocketUtil.getParam(WebsocketUtil.sessionKey, session);
WebsocketUtil.addSession(deviceId, session);
DeviceChannelContext deviceChannelContext = ChannelFactory.getChannelBySerialNo(deviceId);
if (deviceChannelContext != null && (!deviceChannelContext.getCtx().isRemoved())) {
WebsocketUtil.sendMessage(deviceId, AjaxResult.success("ok"));
} else {
WebsocketUtil.sendMessage(deviceId, AjaxResult.success("no"));
}
}
@OnClose
public void onClose(Session session) {
String deviceId = WebsocketUtil.getParam(WebsocketUtil.sessionKey, session);
WebsocketUtil.removeSession(deviceId);
}
@OnMessage
public void onMessage(Session session, String message) {
System.out.println(message);
}
@OnError
public void onError(Session session, Throwable throwable) {
try {
if (session.isOpen()) {
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
throwable.printStackTrace();
}
}
6、前端js页面
var url = "ws://" + window.location.host + "/verifyDevice?deviceId=" + facedeviceCode;
websocket = new WebSocket(url);
websocket.onopen = () => console.log("连接建立");
websocket.onclose = () => console.log("连接关闭");
websocket.onmessage = function (res) {
var obj = eval('(' + res.data + ')');
if (obj && obj.msg == "cardInfo") {
console.info("调用discernToInfo方法");
discernToInfo(obj);
}
else if (obj && obj.msg == "imgInfo") {
console.info("调用imgToInfo方法");
imgToInfo(obj);
}
}
求关注~~~
点关注不迷路,喜欢的朋友们关注支持一下 |
给点继续写的动力,感谢!! |