Spring Boot SockJS应用例子
2020-12-13 15:26
YPE >
标签:注册 start app map tle class socket import 兼容
1.SockJS用javascript实现的socket连接,兼容各种浏览器的WebSocket支持库
2.WebSocket是H5的,不支持H5的浏览器没法使用。
3.SockJS它提供类似于websocket的编程模式但是可以适应不同的浏览器(包括不支持websocket的浏览器)。
后端代码:

-
org.springframework.boot - spring-boot-starter-websocket

- 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") // 扫描那些包得到bean.@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 {
- // 连接继开处理
- @Override
- public void afterConnectionClosed(WebSocketSession arg0, CloseStatus arg1) throws Exception {
- // TODO Auto-generated method stub
- System.out.println("Connection closed..." + arg0.getRemoteAddress().toString());
- }
- // 连接建立处理
- @Override
- public void afterConnectionEstablished(WebSocketSession arg0) throws Exception {
- // TODO Auto-generated method stub
- System.out.println("Connection established..." + arg0.getRemoteAddress().toString());
- }
- // 接收、发送信息处理
- @Override
- public void handleMessage(WebSocketSession arg0, WebSocketMessage> arg1) throws Exception {
- // TODO Auto-generated method stub
- try {
- System.out.println("Req: " + arg1.getPayload());
- // 发送信息
- TextMessage returnMessage = new TextMessage(arg1.getPayload() + " received at server");
- arg0.sendMessage(returnMessage);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 错误处理(客户端突然关闭等接收到的错误)
- @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;
- /**
- * 类描述:拦截器
- */
- 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
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 // 配置类
- @EnableWebSocket // 声明支持websocket
- public class WebSocketConfig implements WebSocketConfigurer {
- @Override
- public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
- // 注册websocket实现类,指定参数访问地址;allowed-origins="*" 允许跨域
- // addHandler是增加处理接口和设定URL
- // addInterceptors是增加拦截器处理(可以不用)
- 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();
- }
- }
前端代码:

- html>
- "UTF-8">
-
Insert title here - var url = "127.0.0.1:8090/";
- var 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;
- function onOpen(openEvent) {
- document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ "OPEN
"; - }
- function onMessage(event) {
- document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ event.data+"
"; - }
- function onError() {
- }
- function onClose() {
- document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ "CLOSE
"; - }
- function doSend() {
- console.log(websocket.readyState);
- if (websocket.readyState == SockJS.OPEN) {
- var msg = document.getElementById("message").value;
- //发送消息
- websocket.send(msg);
- } else {
- alert("连接失败!");
- }
- }
- 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;
- }
-
-
-
日志信息:
-
"console" width="600px">
参考(websocket简单应用):http://wiselyman.iteye.com/blog/2003336
参考(应用例子):http://768992698.iteye.com/blog/2338250
参考(应用例子(TextWebSocketHandler )):http://www.cnblogs.com/likun10579/p/5594828.html
Spring Boot SockJS应用例子
标签:注册 start app map tle class socket import 兼容
原文地址:https://www.cnblogs.com/exmyth/p/11581651.html