Spring Boot SockJS应用例子
1.SockJS用javascript实现的socket连接,兼容各种浏览器的WebSocket支持库
2.WebSocket是H5的,不支持H5的浏览器没法使用。
3.SockJS它提供类似于websocket的编程模式但是可以适应不同的浏览器(包括不支持websocket的浏览器)。
后端代码:
- <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") // 扫描那些包得到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<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 // 配置类
- @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();
- }
- }
前端代码:
- <!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");//建立连接
- } 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<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;
- //发送消息
- 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;
- }
- </script>
- </head>
- <body>
- <div>
- <button id="disconnect" onclick="disconnect()">断开连接</button>
- <button id="send" onclick="doSend()">发送消息</button>
- <button id="reconnect" onclick="reconnect()">重新连接</button>
- </div>
- <div>
- <textarea id="message" style="width: 350px">Here is a message!</textarea>
- </div>
- <div>日志信息:</div>
- <p id="console" width="600px"></p>
- </body>
- </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应用例子的更多相关文章
- Spring Boot SOAP Webservice例子
前言 本文将学习如何利用Spring boot快速创建SOAP webservice服务: 虽然目前REST和微服务越来越流行,但是SOAP在某些情况下,仍然有它的用武之地: 在本篇 spring b ...
- Spring Boot 2 + Redis例子
Redis是一个key-value数据库,支持存储的value类型包括string(字符串).list(链表).set(集合).zset(sorted set --有序集合)和hash(哈希类型).在 ...
- spring boot 微服务例子一
package com.example.hello.demo; import org.springframework.boot.SpringApplication;import org.springf ...
- spring boot整合JWT例子
application.properties jwt.expire_time=3600000 jwt.secret=MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjY34DFDSS ...
- Spring Boot之Hello World
Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不 ...
- spring boot面试问题集锦
译文作者:david 原文链接:https://www.javainuse.com/spring/SpringBootInterviewQuestions Q: 什么是spring boot? A: ...
- 1.Spring Boot入门及其jar包依赖模型分析
Spring Boot介绍 Spring Boot是由Pivotal团队提供的新框架,其设计目的是简化Spring应用的搭建以及开发过程.其目标是: 为所有Spring开发提供一个从根本上更快,且方便 ...
- spring boot整合mybatis+mybatis-plus
Spring boot对于我来说是一个刚接触的新东西,学习过程中,发现这东西还是很容易上手的,Spring boot没配置时会默认使用Spring data jpa,这东西可以说一个极简洁的工具,可是 ...
- 面试那点小事,你从未见过的spring boot面试集锦(附详细答案)
一, 什么是spring boot? 多年来,随着新功能的增加,spring变得越来越复杂.只需访问页面https://spring.io/projects,我们将看到所有在应用程序中使用的不同功能的 ...
随机推荐
- django:资源网站汇总
Django REST framework官网 http://www.sinodocs.cn/ django中文网 https://www.django.cn/
- 10分钟弄懂Raft算法
分布式系统在极大提高可用性.容错性的同时,带来了一致性问题(CAP理论).Raft算法能够解决分布式系统环境下的一致性问题. 我们熟悉的ETCD注册中心就采用了这个算法:你现在看的这篇微信公众号文章, ...
- C#基于RabbitMQ实现客户端之间消息通讯实战演练
一.背景介绍和描述 MQ消息队列已经逐渐成为企业IT系统内部通信的核心手段.它具有低耦合.可靠投递.广播.流量控制.最终一致性等一系列功能,成为异步RPC的主要手段之一.何时需要消息队列?当你需要使用 ...
- 【视频开发】【计算机视觉】doppia编译之三:编译安装opencv库
这里我介绍2种方法 (1)利用别人写好的脚本编译,相对来说省力一点 上Github下载别人写好的脚本文件,网址 https://github.com/jayrambhia/Install-OpenC ...
- 【python开发】利用PIP3的时候出现的问题Fatal error in launcher: Unable to create process using '"'
down voteaccepted I fixed my issue by... downloading Python 3 at the official website and installing ...
- LeetCode 872. 叶子相似的树(Leaf-Similar Trees)
872. 叶子相似的树 872. Leaf-Similar Trees 题目描述 请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个叶值序列. LeetCode872. Leaf- ...
- linux-pdb命令行下python断点调试工具
一般地,我们可以使用如下的方式进入调试(比如我们要调试的源文件为hello.py): 1. 在命令行启动目标程序,加上-m参数. python -m pdb hello.py 这样程序会自动停在第 ...
- 端口占用问题:java.net.BindException: Address already in use: bind
解决方法 方法一:换一个端口 若仍然想要使用该端口,则可以将占用该端口的进程杀死即可. 方法二:杀死占用该端口的进程 若仍然想要使用该端口,则可以将占用该端口的进程杀死即可 查找端口被占用的进程id ...
- c++基础(三)——容器
1. 顺序容器 vector和string将元素保存在连续的内存空间中.由于元素是连续存储的,由元素的下标来计算其地址是非常快速的.但是在这两种容器的中间位置添加或删除元素就非常耗时 list和for ...
- JavaScript进行UTF-8编码与解码
JavaScript本身可通过charCodeAt方法得到一个字符的Unicode编码,并通过fromCharCode方法将Unicode编码转换成对应字符. 但charCodeAt方法得到的应该是一 ...