Sping WebSocket SockJS使用
2019独角兽企业重金招聘Python工程师标准>>>
注意点:
1、Spring Framework从4.0版本开始支持websocket,示例代码使用的是4.1.3
2、SockJs是一个封装的WebSocket实现,可以支持低版本的IE浏览器。
3、SockJs+Spring-WebSocket时,由于SockJs与Spring WebSocket之间采用JSON通讯,需要引入jackson 2的相关jar包。
4、项目需要使用到Spring MVC。
具体代码实现(小例子):
1、Spring WebSocket配置类
Java代码
- package com.watcher.websocket.spring;
- 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="*" 允许跨域
- registry.addHandler(myHandler(), "/ws").addInterceptors(myHandshake()).setAllowedOrigins("*");
- //允许客户端使用SockJS
- registry.addHandler(myHandler(), "/sockjs/ws").addInterceptors(myHandshake()).withSockJS();
- }
- @Bean
- public MyHandler myHandler(){
- return new MyHandler();
- }
- @Bean
- public MyHandshakeInterceptor myHandshake(){
- return new MyHandshakeInterceptor();
- }
- }
2、Handler类实现(用于处理具体的消息)
Java代码
- package com.watcher.websocket.spring;
- 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;
- //extending either TextWebSocketHandler orBinaryWebSocketHandler
- 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;
- }
- }
3、握手拦截器实现(拦截器...)
Java代码
- package com.watcher.websocket.spring;
- 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;
- /**
- *
- * 类描述:握手拦截器
- * com.watcher.websocket.spring MyHandshakeInterceptor
- * Created by 78098 on 2016年11月15日.
- * version 1.0
- */
- 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);
- }
- }
4、页面
Html代码
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- <script type="text/javascript" src="./plugin/sockjs/sockjs-1.1.1.js"></script>
- <script type="text/javascript">
- var url = "192.168.120.37:8080/springMybatis";
- 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" οnclick="disconnect()">断开连接</button>
- <button id="send" οnclick="doSend()">发送消息</button>
- <button id="reconnect" οnclick="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>
转载于:https://my.oschina.net/martin123/blog/869053
Sping WebSocket SockJS使用相关推荐
- 基于spring websocket+sockjs实现的长连接请求
1.前言 页面端通常有需求想要准实时知道后台数据的一个变化情况,比如扫码登录场景,或者跳转到网银支付场景,在旧有的短轮训实现下,通常造成大量的不必要请求和查询,这里基于spring websocket ...
- WebSocket+SockJs+STMOP
应用场景 WebSocket 1 编写Handler类 2 拦截器的实现 3 WebSocketConfig配置 4 客户端配置 5 Bad Code 6 nginx配置 SockJs 1 WebSo ...
- ws配置 zuul_zuul+websocket+sockjs
需要实现前端页面->zuul网关->消息服务,建立websocket连接 使用spring-cloud-netflix-zuul-websocket 实现zuul网关层对websocket ...
- springboot+websocket+sockjs进行消息推送【基于STOMP协议】
1.浅谈WebSocket WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就可以建立一条快速通道,两者就可以实现数据互传了.说白了,就是打 ...
- 在vue中使用SockJS实现webSocket通信
最近接到一个业务需求,需要做一个聊天信息的实时展示的界面,这就需要和服务器端建立webSocket连接,从而实现数据的实时获取和视图的实时刷新.在此将我的实现记录下来,希望可以给有同样需求的人一些帮助 ...
- c语言实现stomp协议客户端,在vue中使用SockJS实现webSocket通信
最近接到一个业务需求,需要做一个聊天信息的实时展示的界面,这就需要和 服务器 端建立webSocket连接,从而实现数据的实时获取和视图的实时刷新.在此将我的实现记录下来,希望可以给有同样需求的人一些 ...
- Spring消息之WebSocket
一.WebSocket简介 WebSocket 的定义?WebSocket是HTML5下一种全双工通信协议.在建立连接后,WebSocket服务器端和客户端都能主动的向对方发送和接收数据,就像Sock ...
- spring WebSocket详解
场景 websocket是Html5新增加特性之一,目的是浏览器与服务端建立全双工的通信方式, 解决http请求-响应带来过多的资源消耗,同时对特殊场景应用提供了全新的实现方式, 比如聊天.股票交易. ...
- spring+websocket综合(springMVC+spring+MyBatis这是SSM框架和websocket集成技术)
java-websocket该建筑是easy.儿童无用的框架可以在这里下载主线和个人教学好java-websocket计划: Apach Tomcat 8.0.3+MyEclipse+maven+JD ...
最新文章
- 插值方法——Lagrange插值公式
- 问题 1045: [编程入门]自定义函数之整数处理
- 只要沾上婚恋焦虑,她们就王者变青铜
- ViewState笔记
- shapley值法 - 用边际收益衡量每个人的贡献
- [Ext JS6]多类型设备开发
- 远程服务器返回错误 (411) 所需的长度。
- 用SIR模型处理新冠疫情
- 网络爬虫设计中需要注意的几个问题
- PPT计算机原理结构初步,测量实践初步(赖丽娟).ppt
- 通过SQL语句数据库简繁体转换
- Linux开启root用户
- 有限域(2)——理想和商环
- 车载网络测试 - 车载以太网 - ARP详细解析
- 服务器端测试经验分享
- gis核密度分析工具_抓取公共服务设施POI后,用GIS进行核密度分析的可视化过程...
- 专门画像素图的软件_新世纪像素画设计软件,你值得一试!
- 网际协议IP简单总结
- meterpreter使用详解
- NLS(National Language Support)
热门文章
- 开源网络备份软件bacula学习笔记
- ssh时出现 Agent admitted failure to sign using the key
- 如何建立顺畅的项目流程
- win10软件拒绝访问删不掉_进程拒绝访问怎么结束_win10关闭进程拒绝访问的处理方法...
- Python基础知识详解
- 为什么Python是2021最值得学的编程语言?
- mvn 默认scope_maven scope 的作用
- android 联系人编辑界面,android – 以编程方式编辑联系人的姓名/电话号码
- 在云中进行灾难恢复的五种有效方式
- Mysql 主从延时监控(pt-heartbeat)详解