websocket前台实现代码,保存为html执行就好
html代码来自:https://blog.csdn.net/M348915654/article/details/53616837
<html> <head> <meta charset="utf-8"> <title>WebSoket Demo</title> <script type="text/JavaScript"> // tips: WebSocket 调试脚本 var WebSocket = WebSocket || window.WebSocket || window.MozWebSocket; // 验证浏览器是否支持WebSocket协议 if (!WebSocket) { alert("WebSocket not supported by this browser!"); } else { var g_ws = null; function Display() { // 载入上次记录的数据 //... console.log("websocket 测试"); } var log = function (s) { if (document.readyState !== "complete") { log.buffer.push(s); } else { document.getElementById("contentId").value = (s + " ") + document.getElementById("contentId").value } } function CreateConnect () { var msg = document.getElementById("wsUrlId"); console.log("CreateConnect(), url: " + msg.value); if (g_ws == null) { var wsUrlValue = msg.value; try { g_ws = new WebSocket(wsUrlValue); // 监听消息 g_ws.onmessage = function (event) { //valueLabel.innerHTML+ = event.data; log("onmessage(), 接收到服务器消息: " + event.data); }; // 打开 WebSocket g_ws.onclose = function (event) { //WebSocket Status:: Socket Closed log("onclose(), Socket 已关闭!"); g_ws = null; }; // 打开WebSocket g_ws.onopen = function (event) { //WebSocket Status:: Socket Open // 发送一个初始化消息 // g_ws.send("Hello, Server!"); log("onopen(), Socket 连接成功!"); }; g_ws.onerror = function (event) { //WebSocket Status:: Error was reported log("onerror(), Socket 发生错误!"); }; } catch (e) { g_ws = null; log("连接异常, 重置 websocket"); } } } function SendMsg() { var msg = document.getElementById("messageId"); console.log("SendMsg(), msg: " + msg.value); if (g_ws != null) { //alert(msg.value); log("发送 Socket 消息: " + msg.value); g_ws.send(msg.value); } else { log("Socket 还未创建!, msg: " + msg.value); } } function CloseConnect () { console.log("CloseConnect()"); if (g_ws != null) { g_ws.close(); } } } </script> </head> <body onload="Display()"> <div id="valueLabel"></div> <textarea rows="20" cols="30" id="contentId"></textarea> <br/> <input name="wsUrl" id="wsUrlId" value="ws://localhost:8888/websocket"/> <button id="createButton" onClick="javascript:CreateConnect()">Create</button> <button id="closeButton" onClick="javascript:CloseConnect()">Close</button> <br/> <input name="message" id="messageId" value="Hello, Server!"/> <button id="sendButton" onClick="javascript:SendMsg()">Send</button> </body> </html>
方法一
配置:
/** * webSocket 方法一 */ @Configuration @ConditionalOnWebApplication public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
实现:
/** * webSocket 方法一 */ @Slf4j @ServerEndpoint(value = "/websocket") @Component public 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 @EnableWebSocket public 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, Map<String, Object> map) 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 方法二 */ @Component public class MyWebSocketHandler implements WebSocketHandler { private static final Map<String ,WebSocketSession> userMap=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; } }