/** * 创建连接 * @param session */ @OnOpen public void start(Session session) { try { this.session = session; this.id = UUID.randomUUID().toString(); logger.info("连接websocket,id=" + this.id); } catch (Exception ex) { logger.error("WebSocket.start(Session session)方法发生错误:" + ExceptionUtil.getStackMsg(ex)); } } 其中@OnOpen表示创建连接 /** * 关闭连接 */ @OnClose public void end() { try { logger.info("关闭WebSocket,id=" + this.getId()); WebSocketPool.removeWebSocket(null, this); try { if (this.session != null) { this.session.close(); } } catch (IllegalStateException e) { logger.info("WebSocket前端断开连接"); } catch (Exception e) { logger.error("WebSocket关闭连接出错", e); } } catch (Exception ex) { logger.error("WebSocket.end()方法发生错误:" + ExceptionUtil.getStackMsg(ex)); } } @OnOpen表示关闭连接 /** * 接收数据 * @param message */ @OnMessage public void incoming(String message) { try { // webSocketProcesser.process(message, this); } catch (Exception ex) { logger.error("WebSocket.incoming(String message)方法发生错误:" + ExceptionUtil.getStackMsg(ex)); } } 其中 @OnMessage表示的是接收数据信息。 /** * 发送数据 * @param msg * @throws IOException */ public void sendMsg(String msg) throws IOException{ try { try { if(this.session.isOpen()){ this.session.getBasicRemote().sendText(msg); } // this.session.getBasicRemote().flushBatch(); } catch (IOException e) { this.session.close(); WebSocketPool.removeWebSocket(null, this); e.printStackTrace(); } } catch (Exception ex) { logger.error("WebSocket.sendMsg(String msg)方法发生错误:" + ExceptionUtil.getStackMsg(ex)); } }
java搭建websocket_webSocket.java创建连接和关闭连接
最新推荐文章于 2024-06-10 22:10:39 发布