1.SockJS用javascript实现的socket连接,兼容各种浏览器的WebSocket支持库
2.WebSocket是H5的,不支持H5的浏览器没法使用。
3.SockJS它提供类似于websocket的编程模式但是可以适应不同的浏览器(包括不支持websocket的浏览器)。

后端代码:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>
  1. package com.cesmart;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.context.annotation.ComponentScan;
  6. @EnableAutoConfiguration
  7. @ComponentScan(basePackages = "com.cesmart") // 扫描那些包得到bean.@ComponentScan({"com.teradata.notification","com.teradata.dal"})
  8. public class Application {
  9. public static void main(String[] args) {
  10. ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
  11. }
  12. }
  1. package com.cesmart.config;
  2. import org.springframework.web.socket.CloseStatus;
  3. import org.springframework.web.socket.TextMessage;
  4. import org.springframework.web.socket.WebSocketHandler;
  5. import org.springframework.web.socket.WebSocketMessage;
  6. import org.springframework.web.socket.WebSocketSession;
  7. public class MyHandler implements WebSocketHandler {
  8. // 连接继开处理
  9. @Override
  10. public void afterConnectionClosed(WebSocketSession arg0, CloseStatus arg1) throws Exception {
  11. // TODO Auto-generated method stub
  12. System.out.println("Connection closed..." + arg0.getRemoteAddress().toString());
  13. }
  14. // 连接建立处理
  15. @Override
  16. public void afterConnectionEstablished(WebSocketSession arg0) throws Exception {
  17. // TODO Auto-generated method stub
  18. System.out.println("Connection established..." + arg0.getRemoteAddress().toString());
  19. }
  20. // 接收、发送信息处理
  21. @Override
  22. public void handleMessage(WebSocketSession arg0, WebSocketMessage<?> arg1) throws Exception {
  23. // TODO Auto-generated method stub
  24. try {
  25. System.out.println("Req: " + arg1.getPayload());
  26. // 发送信息
  27. TextMessage returnMessage = new TextMessage(arg1.getPayload() + " received at server");
  28. arg0.sendMessage(returnMessage);
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. // 错误处理(客户端突然关闭等接收到的错误)
  34. @Override
  35. public void handleTransportError(WebSocketSession arg0, Throwable arg1) throws Exception {
  36. // TODO Auto-generated method stub
  37. if (arg0.isOpen()) {
  38. arg0.close();
  39. }
  40. System.out.println(arg1.toString());
  41. System.out.println("WS connection error,close...");
  42. }
  43. @Override
  44. public boolean supportsPartialMessages() {
  45. // TODO Auto-generated method stub
  46. return false;
  47. }
  48. }
  1. package com.cesmart.config;
  2. import java.util.Map;
  3. import org.springframework.http.server.ServerHttpRequest;
  4. import org.springframework.http.server.ServerHttpResponse;
  5. import org.springframework.web.socket.WebSocketHandler;
  6. import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
  7. /**
  8. * 类描述:拦截器
  9. */
  10. public class MyHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
  11. @Override
  12. public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
  13. Exception ex) {
  14. // TODO Auto-generated method stub
  15. System.out.println("After handshake " + request.getRemoteAddress().toString());
  16. super.afterHandshake(request, response, wsHandler, ex);
  17. }
  18. @Override
  19. public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler,
  20. Map<String, Object> map) throws Exception {
  21. // TODO Auto-generated method stub
  22. System.out.println("Before handshake " + request.getRemoteAddress().toString());
  23. return super.beforeHandshake(request, response, handler, map);
  24. }
  25. }
  1. package com.cesmart.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  5. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  6. import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
  7. @Configuration // 配置类
  8. @EnableWebSocket // 声明支持websocket
  9. public class WebSocketConfig implements WebSocketConfigurer {
  10. @Override
  11. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  12. // 注册websocket实现类,指定参数访问地址;allowed-origins="*" 允许跨域
  13. // addHandler是增加处理接口和设定URL
  14. // addInterceptors是增加拦截器处理(可以不用)
  15. registry.addHandler(myHandler(), "/ws").addInterceptors(myHandshake()).setAllowedOrigins("*");
  16. registry.addHandler(myHandler(), "/sockjs/ws").addInterceptors(myHandshake()).withSockJS();
  17. registry.addHandler(myHandler(), "/ws2").setAllowedOrigins("*");
  18. registry.addHandler(myHandler(), "/sockjs/ws2").setAllowedOrigins("*").withSockJS();
  19. }
  20. @Bean
  21. public MyHandler myHandler() {
  22. return new MyHandler();
  23. }
  24. @Bean
  25. public MyHandshakeInterceptor myHandshake() {
  26. return new MyHandshakeInterceptor();
  27. }
  28. }

前端代码:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. <script type="text/javascript" src="//cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
  7. <script type="text/javascript">
  8. var url = "127.0.0.1:8090/";
  9. var websocket = null;
  10. if ('WebSocket' in window) {
  11. websocket = new WebSocket("ws://" + url + "/ws");//建立连接
  12. } else {
  13. websocket = new SockJS("http://" + url + "/sockjs/ws");//建立连接
  14. }
  15. //建立连接处理
  16. websocket.onopen = onOpen;
  17. //接收处理
  18. websocket.onmessage = onMessage;
  19. //错误处理
  20. websocket.onerror = onError;
  21. //断开连接处理
  22. websocket.onclose = onClose;
  23. function onOpen(openEvent) {
  24. document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ "OPEN<br/>";
  25. }
  26. function onMessage(event) {
  27. document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ event.data+"<br/>";
  28. }
  29. function onError() {
  30. }
  31. function onClose() {
  32. document.getElementById("console").innerHTML = document.getElementById("console").innerHTML+ "CLOSE<br/>";
  33. }
  34. function doSend() {
  35. console.log(websocket.readyState);
  36. if (websocket.readyState == SockJS.OPEN) {
  37. var msg = document.getElementById("message").value;
  38. //发送消息
  39. websocket.send(msg);
  40. } else {
  41. alert("连接失败!");
  42. }
  43. }
  44. function disconnect(){
  45. if (websocket != null) {
  46. websocket.close();
  47. websocket = null;
  48. }
  49. }
  50. function reconnect(){
  51. if (websocket != null) {
  52. websocket.close();
  53. websocket = null;
  54. }
  55. if ('WebSocket' in window) {
  56. websocket = new WebSocket("ws://" + url + "/ws");
  57. } else {
  58. websocket = new SockJS("http://" + url + "/sockjs/ws");
  59. }
  60. websocket.onopen = onOpen;
  61. websocket.onmessage = onMessage;
  62. websocket.onerror = onError;
  63. websocket.onclose = onClose;
  64. }
  65. </script>
  66. </head>
  67. <body>
  68. <div>
  69. <button id="disconnect" onclick="disconnect()">断开连接</button>
  70. <button id="send" onclick="doSend()">发送消息</button>
  71. <button id="reconnect" onclick="reconnect()">重新连接</button>
  72. </div>
  73. <div>
  74. <textarea id="message" style="width: 350px">Here is a message!</textarea>
  75. </div>
  76. <div>日志信息:</div>
  77. <p id="console" width="600px"></p>
  78. </body>
  79. </html>

参考(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应用例子的更多相关文章

  1. Spring Boot SOAP Webservice例子

    前言 本文将学习如何利用Spring boot快速创建SOAP webservice服务: 虽然目前REST和微服务越来越流行,但是SOAP在某些情况下,仍然有它的用武之地: 在本篇 spring b ...

  2. Spring Boot 2 + Redis例子

    Redis是一个key-value数据库,支持存储的value类型包括string(字符串).list(链表).set(集合).zset(sorted set --有序集合)和hash(哈希类型).在 ...

  3. spring boot 微服务例子一

    package com.example.hello.demo; import org.springframework.boot.SpringApplication;import org.springf ...

  4. spring boot整合JWT例子

    application.properties jwt.expire_time=3600000 jwt.secret=MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjY34DFDSS ...

  5. Spring Boot之Hello World

    Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不 ...

  6. spring boot面试问题集锦

    译文作者:david  原文链接:https://www.javainuse.com/spring/SpringBootInterviewQuestions Q: 什么是spring boot? A: ...

  7. 1.Spring Boot入门及其jar包依赖模型分析

    Spring Boot介绍 Spring Boot是由Pivotal团队提供的新框架,其设计目的是简化Spring应用的搭建以及开发过程.其目标是: 为所有Spring开发提供一个从根本上更快,且方便 ...

  8. spring boot整合mybatis+mybatis-plus

    Spring boot对于我来说是一个刚接触的新东西,学习过程中,发现这东西还是很容易上手的,Spring boot没配置时会默认使用Spring data jpa,这东西可以说一个极简洁的工具,可是 ...

  9. 面试那点小事,你从未见过的spring boot面试集锦(附详细答案)

    一, 什么是spring boot? 多年来,随着新功能的增加,spring变得越来越复杂.只需访问页面https://spring.io/projects,我们将看到所有在应用程序中使用的不同功能的 ...

随机推荐

  1. 解决python写入mysql中datetime类型遇到的问题

    解决python写入mysql中datetime类型遇到的问题 刚开始使用python,还不太熟练,遇到一个datetime数据类型的问题: 在mysql数据库中,有一个datetime类型的字段用于 ...

  2. npm创建angular项目

    1.首先保证你本地的 node 环境 是ok的哦. 2.安装 angular-cli    命令  npm install -g @angular/cli.安装完成后,ng version 查看版本, ...

  3. Altera FPGA 远程升级有关的几个IP的使用

    在做在线远程升级的时候,一般需要两步:1.将数据写到外挂的flash中.2重新启动FPGA配置. 不过要做到远程升级,一般需要在原始程序中就考虑到加入远程升级模块,remote updata IP, ...

  4. Python3 列表list合并的4种方法

    方法1: 直接使用"+"号合并列表 aList = [1,2,3] bList = ['www', 'pythontab.com'] cList = aList + bList   ...

  5. hdu 2841 题解

    题目 题意:就是问在一个$ n* m $的矩阵中站在 $ (0,0) $ 能看到几个整数点. 很明显如果有两个平行向量 $ \vec{a}=(x_1,y_1) $ ,$ \vec{b}=(x_2,y_ ...

  6. Jmeter参数化(_csvread函数、CSV Data Set Config)

    方法一.Jmeter自带的函数助手——_CSVRead函数 1.数据准备:先在excel存储数据,保存格式选择csv格式.或在记事本存储数据,列之间用英文逗号分隔,保存为txt 2.使用_csvrea ...

  7. net core quartz调度 warp打包 nssm部署到windowsservice

    介绍下一款vue.js实现的基于core2.1 quartz.net调度框架,独立部署不依赖数据库,只需要实现不同业务接口,配置调度时间即可 github:https://github.com/cq- ...

  8. windows10 iis浏览wcf报404.3错误

    报错:HTTP错误404.3-Not Found 由于扩展配置问题而无法提供您请求的页面.如果该页面是脚本,请添加处理程序.如果应下载文件,请添加MIME映射. 解决步骤如下: 控制面板->打开 ...

  9. wpf 对控件进行截图,获取快照

    有时候我们项目,在执行某个操作后,会生成一些数据结果,如报表一类的东西,我们需要对结果进行保存,甚至是生成word文档. 那么首先获取到控件快照就最基本的条件. 生成快照的静态方法类 using Sy ...

  10. ASP.NET Core & 双因素验证2FA 实战经验分享

    必读 本文源码核心逻辑使用AspNetCore.Totp,为什么不使用AspNetCore.Totp而是使用源码封装后面将会说明. 为了防止不提供原网址的转载,特在这里加上原文链接: https:// ...