1. The socket connection implemented by SockJS in javascript is compatible with the WebSocket support library of various browsers 2. WebSocket
is H5, and browsers that do not support H5 cannot use it.
3.SockJS It provides a programming mode similar to websocket but can adapt to different browsers (including browsers that do not support websocket).
Backend code:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
package com.cesmart; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan(basePackages = "com.cesmart") // scan those packages for beans.@ComponentScan({"com.teradata.notification","com.teradata.dal"}) public class Application { public static void main(String[] args) { ApplicationContext applicationContext = SpringApplication.run(Application.class, args); } }
package com.cesmart.config; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketMessage; import org.springframework.web.socket.WebSocketSession; public class MyHandler implements WebSocketHandler { // connection continue processing @Override public void afterConnectionClosed(WebSocketSession arg0, CloseStatus arg1) throws Exception { // TODO Auto-generated method stub System.out.println("Connection closed..." + arg0.getRemoteAddress().toString()); } // connection establishment processing @Override public void afterConnectionEstablished(WebSocketSession arg0) throws Exception { // TODO Auto-generated method stub System.out.println("Connection established..." + arg0.getRemoteAddress().toString()); } // Receive and send information processing @Override public void handleMessage(WebSocketSession arg0, WebSocketMessage<?> arg1) throws Exception { // TODO Auto-generated method stub try { System.out.println("Req: " + arg1.getPayload()); // send Message TextMessage returnMessage = new TextMessage(arg1.getPayload() + " received at server"); arg0.sendMessage(returnMessage); } catch (Exception e) { e.printStackTrace (); } } // Error handling (received errors such as abrupt client shutdown, etc.) @Override public void handleTransportError(WebSocketSession arg0, Throwable arg1) throws Exception { // TODO Auto-generated method stub if (arg0.isOpen()) { arg0.close(); } System.out.println(arg1.toString()); System.out.println("WS connection error,close..."); } @Override public boolean supportsPartialMessages() { // TODO Auto-generated method stub return false; } }
package com.cesmart.config; import java.util.Map; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; /** * Class description: Interceptor */ public class MyHandshakeInterceptor extends HttpSessionHandshakeInterceptor { @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { // TODO Auto-generated method stub System.out.println("After handshake " + request.getRemoteAddress().toString()); super.afterHandshake(request, response, wsHandler, ex); } @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Map<String, Object> map) throws Exception { // TODO Auto-generated method stub System.out.println("Before handshake " + request.getRemoteAddress().toString()); return super.beforeHandshake(request, response, handler, map); } }
package com.cesmart.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration // configuration class @EnableWebSocket // declares support for websocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { // Register the websocket implementation class and specify the parameter access address; allowed-origins="*" allows cross-domain // addHandler is to increase the processing interface and set the URL // addInterceptors is to add interceptor processing (can not be used) registry.addHandler(myHandler(), "/ws").addInterceptors(myHandshake()).setAllowedOrigins("*"); registry.addHandler(myHandler(), "/sockjs/ws").addInterceptors(myHandshake()).withSockJS(); registry.addHandler(myHandler(), "/ws2").setAllowedOrigins("*"); registry.addHandler(myHandler(), "/sockjs/ws2").setAllowedOrigins("*").withSockJS(); } @Bean public MyHandler myHandler() { return new MyHandler(); } @Bean public MyHandshakeInterceptor myHandshake() { return new MyHandshakeInterceptor(); } }
Front-end code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="//cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script> <script type="text/javascript"> var url = "127.0.0.1:8090/"; var websocket = null; if ('WebSocket' in window) { websocket = new WebSocket("ws://" + url + "/ws");//establish a connection } else { websocket = new SockJS("http://" + url + "/sockjs/ws");//establish a connection } //establish connection processing websocket.onopen = onOpen; //Receive processing websocket.onmessage = onMessage; //error handling websocket.onerror = onError; // disconnect processing websocket.onclose = onClose; function onOpen(openEvent) { document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ "OPEN<br/>"; } function onMessage(event) { document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ event.data+"<br/>"; } function onError() { } function onClose() { document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ "CLOSE<br/>"; } function doSend () { console.log(websocket.readyState); if (websocket.readyState == SockJS.OPEN) { var msg = document.getElementById("message").value; //send messages websocket.send(msg); } else { alert("Connection failed!"); } } function disconnect(){ if (websocket != null) { websocket.close(); websocket = null; } } function reconnect(){ if (websocket != null) { websocket.close(); websocket = null; } if ('WebSocket' in window) { websocket = new WebSocket("ws://" + url + "/ws"); } else { websocket = new SockJS("http://" + url + "/sockjs/ws"); } websocket.onopen = onOpen; websocket.onmessage = onMessage; websocket.onerror = onError; websocket.onclose = onClose; } </script> </head> <body> <div> <button id="disconnect" onclick="disconnect()">断开连接</button> <button id="send" onclick="doSend()">Send message</button> <button id="reconnect" onclick="reconnect()">重新连接</button> </div> <div> <textarea id="message" style="width: 350px">Here is a message!</textarea> </div> <div>Log information:</div> <p id="console" width="600px"></p> </body> </html>
Reference (websocket simple application): http://wiselyman.iteye.com/blog/2003336
Reference (application example): http://768992698.iteye.com/blog/2338250
Reference (application example (TextWebSocketHandler)): http: //www.cnblogs.com/likun10579/p/5594828.html