java-webSocket
例:
JS:
var proName = '${pageContext.request.contextPath}'; var ws = new WebSocket('ws://'+ window.location.host + proName +'/confservice/confWebSocketService/huiyifuwu');//new webSocket表示已连接 webSocket(); //建立消息连接 function webSocket() { ws.onopen = function(evt){ //心跳检测重置 heartCheck.reset().start(); //ws.send("send123"); }; ws.onmessage = function(evt) { var data = evt.data; if (data != "ping!") { splitData(data); } //心跳检测重置 heartCheck.reset().start(); } ws.onclose = function(evt) { ws.close(); } } function splitData(data) { } //心跳检测 var heartCheck = { timeout: 180000,//180秒 timeoutObj: null, reset: function(){ clearTimeout(this.timeoutObj); return this; }, start: function(){ this.timeoutObj = setTimeout(function(){ //这里发送一个心跳,后端收到后,返回一个心跳消息, //onmessage拿到返回的心跳就说明连接正常 ws.send("ping!"); }, this.timeout) } } // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function() { ws.close(); }
java:
@Component//申明为spring组件 @ServerEndpoint("/confservice/confWebSocketService/{id}")//webSocket连接地址 public class ConfWebSocketService { private static final Logger logger = Logger.getLogger(ConfWebSocketService.class); private static Map<Session, String> sessionMaps = new HashMap<>(); private static Session sessionf; private static List<User> allUserMS = new ArrayList<>(); private static List<User> allUserWY = new ArrayList<>(); @Autowired private IUserService userService; // 静态初使化当前类 public static ConfWebSocketService confWebSocketService; //注解@PostConstruct,这样方法就会在Bean初始化之后被Spring容器执行 @PostConstruct public void init() { confWebSocketService = this; } /** * 连接成功调用 * @param session */ @OnOpen public void onOpen(Session session, @PathParam("id") String id) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { sessionf = session; sessionMaps.put(session, id); } catch (Exception e) { logger.debug("webSocket连接异常:"+e.getMessage()); e.printStackTrace(); } } }); thread.start(); } /** * 关闭连接调用 */ @OnClose public void onClose(Session session) { Thread thread = new Thread(new Runnable() { @Override public void run() { sessionMaps.remove(session); } }); thread.start(); } /** * 收到客户端消息调用 * @param message * @param session */ @OnMessage public void onMessage(String message,Session session) { if (message.equals("ping!")) { //保持和会议服务长连接 sendMessage(message,"0"); } else if(message.equals("yuyin!")) { //保持和语音识别长连接 sendMessage(message,"2"); } } /** * 出现错误调用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); } /** * 发送消息(自定义的方法) */ public static void sendMessage(String message,String flag) { try { //session.getBasicRemote().sendText(message);//同步发送消息 if (flag.equals("1") || flag.equals("2")) { Role role =new Role(); if (flag.equals("1")) { role.setType("2"); if (allUserMS.size() == 0) { allUserMS = confWebSocketService.userService.getUserByRole(role); } } else { role.setType("0"); if (allUserWY.size() == 0) { allUserWY = confWebSocketService.userService.getUserByRole(role); } } } Set<Map.Entry<Session,String>> entrySet = sessionMaps.entrySet(); for (Entry<Session, String> map : entrySet) { String checkId = map.getValue(); if (flag.equals("0") && checkId.equals("huiyifuwu")) { sessionf = map.getKey(); sessionf.getAsyncRemote().sendText(message);//异步发送消息 break; } else if (flag.equals("1") && allUserMS.size() > 0) { for (User user : allUserMS) { if (checkId.equals(user.getId())) { sessionf = map.getKey(); sessionf.getAsyncRemote().sendText(message);//异步发送消息 break; } } } else if (flag.equals("2") && allUserWY.size() > 0) { for (User user : allUserWY) { if (checkId.equals(user.getId())) { sessionf = map.getKey(); sessionf.getAsyncRemote().sendText(message);//异步发送消息 break; } } } } } catch (Exception e) { e.printStackTrace(); } } }
https访问时,需要添加nginx代理
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步