websocket前台实现代码,保存为html执行就好
html代码来自:https://blog.csdn.net/M348915654/article/details/53616837
WebSoket Demo
方法一
配置:
/** * webSocket 方法一 */@Configuration@ConditionalOnWebApplicationpublic class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }}
实现:
/** * webSocket 方法一 */@Slf4j@ServerEndpoint(value = "/websocket")@Componentpublic class WebSocketServer { /** * 连接建立成功调用的方法 */ @OnOpen public void onOpen(Session session) { } /** * 连接关闭调用的方法 */ @OnClose public void onClose() { webSocketSet.remove(this); //从set中删除 } /** * 收到客户端消息后调用的方法 * * @param message 客户端发送过来的消息 */ @OnMessage public void onMessage(String message, Session session) { } /** * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { }}
方法二:
配置
/** * webSocket方法二 * @author tongxiabin */@Component@EnableWebMvc@EnableWebSocketpublic class WebSocketConfig2 implements WebSocketConfigurer { @Resource private MyWebSocketHandler handler; @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(handler, "/wsMy").addInterceptors(new HandshakeInterceptor() { @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Mapmap) throws Exception { System.out.println("registerWebSocketHandlers-beforeHandshake"); serverHttpResponse.setStatusCode(HttpStatus.OK); return true; } @Override public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) { System.out.println("registerWebSocketHandlers-afterHandshake"); } }).setAllowedOrigins("*"); }}
实现:
/** * webSocket 方法二 */@Componentpublic class MyWebSocketHandler implements WebSocketHandler { private static final MapuserMap=new HashMap<>(); @Override public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception { String jspCode = (String )webSocketSession.getAttributes().get("jspCode"); if(userMap.get(jspCode)==null){ System.out.println(jspCode); userMap.put(jspCode,webSocketSession); } } @Override public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage webSocketMessage) throws Exception { System.out.println("handleMessage"); } @Override public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception { System.out.println("handleTransportError"); } @Override public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception { System.out.println("afterConnectionClosed"); } @Override public boolean supportsPartialMessages() { return false; }}