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代码

  1. package com.watcher.websocket.spring;
  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. registry.addHandler(myHandler(), "/ws").addInterceptors(myHandshake()).setAllowedOrigins("*");
  14. //允许客户端使用SockJS
  15. registry.addHandler(myHandler(), "/sockjs/ws").addInterceptors(myHandshake()).withSockJS();
  16. }
  17. @Bean
  18. public MyHandler myHandler(){
  19. return new MyHandler();
  20. }
  21. @Bean
  22. public MyHandshakeInterceptor myHandshake(){
  23. return new MyHandshakeInterceptor();
  24. }
  25. }

2、Handler类实现(用于处理具体的消息)

Java代码

  1. package com.watcher.websocket.spring;
  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. //extending either TextWebSocketHandler orBinaryWebSocketHandler
  8. public class MyHandler implements WebSocketHandler {
  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. @Override
  15. public void afterConnectionEstablished(WebSocketSession arg0) throws Exception {
  16. // TODO Auto-generated method stub
  17. System.out.println("Connection established..."+arg0.getRemoteAddress().toString());
  18. }
  19. @Override
  20. public void handleMessage(WebSocketSession arg0, WebSocketMessage<?> arg1) throws Exception {
  21. // TODO Auto-generated method stub
  22. try {
  23. System.out.println("Req: "+arg1.getPayload());
  24. TextMessage returnMessage = new TextMessage(arg1.getPayload()
  25. + " received at server");
  26. arg0.sendMessage(returnMessage);
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. @Override
  32. public void handleTransportError(WebSocketSession arg0, Throwable arg1) throws Exception {
  33. // TODO Auto-generated method stub
  34. if(arg0.isOpen()){
  35. arg0.close();
  36. }
  37. System.out.println(arg1.toString());
  38. System.out.println("WS connection error,close...");
  39. }
  40. @Override
  41. public boolean supportsPartialMessages() {
  42. // TODO Auto-generated method stub
  43. return false;
  44. }
  45. }

3、握手拦截器实现(拦截器...)

Java代码

  1. package com.watcher.websocket.spring;
  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. * com.watcher.websocket.spring  MyHandshakeInterceptor
  11. * Created by 78098 on 2016年11月15日.
  12. * version 1.0
  13. */
  14. public class MyHandshakeInterceptor extends HttpSessionHandshakeInterceptor{
  15. @Override
  16. public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
  17. // TODO Auto-generated method stub
  18. System.out.println("After handshake "+request.getRemoteAddress().toString());
  19. super.afterHandshake(request, response, wsHandler, ex);
  20. }
  21. @Override
  22. public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler handler, Map<String, Object> map) throws Exception {
  23. // TODO Auto-generated method stub
  24. System.out.println("Before handshake "+request.getRemoteAddress().toString());
  25. return super.beforeHandshake(request, response, handler, map);
  26. }
  27. }

4、页面

Html代码

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

转载于:https://my.oschina.net/martin123/blog/869053

Sping WebSocket SockJS使用相关推荐

  1. 基于spring websocket+sockjs实现的长连接请求

    1.前言 页面端通常有需求想要准实时知道后台数据的一个变化情况,比如扫码登录场景,或者跳转到网银支付场景,在旧有的短轮训实现下,通常造成大量的不必要请求和查询,这里基于spring websocket ...

  2. WebSocket+SockJs+STMOP

    应用场景 WebSocket 1 编写Handler类 2 拦截器的实现 3 WebSocketConfig配置 4 客户端配置 5 Bad Code 6 nginx配置 SockJs 1 WebSo ...

  3. ws配置 zuul_zuul+websocket+sockjs

    需要实现前端页面->zuul网关->消息服务,建立websocket连接 使用spring-cloud-netflix-zuul-websocket 实现zuul网关层对websocket ...

  4. springboot+websocket+sockjs进行消息推送【基于STOMP协议】

    1.浅谈WebSocket WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就可以建立一条快速通道,两者就可以实现数据互传了.说白了,就是打 ...

  5. 在vue中使用SockJS实现webSocket通信

    最近接到一个业务需求,需要做一个聊天信息的实时展示的界面,这就需要和服务器端建立webSocket连接,从而实现数据的实时获取和视图的实时刷新.在此将我的实现记录下来,希望可以给有同样需求的人一些帮助 ...

  6. c语言实现stomp协议客户端,在vue中使用SockJS实现webSocket通信

    最近接到一个业务需求,需要做一个聊天信息的实时展示的界面,这就需要和 服务器 端建立webSocket连接,从而实现数据的实时获取和视图的实时刷新.在此将我的实现记录下来,希望可以给有同样需求的人一些 ...

  7. Spring消息之WebSocket

    一.WebSocket简介 WebSocket 的定义?WebSocket是HTML5下一种全双工通信协议.在建立连接后,WebSocket服务器端和客户端都能主动的向对方发送和接收数据,就像Sock ...

  8. spring WebSocket详解

    场景 websocket是Html5新增加特性之一,目的是浏览器与服务端建立全双工的通信方式, 解决http请求-响应带来过多的资源消耗,同时对特殊场景应用提供了全新的实现方式, 比如聊天.股票交易. ...

  9. spring+websocket综合(springMVC+spring+MyBatis这是SSM框架和websocket集成技术)

    java-websocket该建筑是easy.儿童无用的框架可以在这里下载主线和个人教学好java-websocket计划: Apach Tomcat 8.0.3+MyEclipse+maven+JD ...

最新文章

  1. 插值方法——Lagrange插值公式
  2. 问题 1045: [编程入门]自定义函数之整数处理
  3. 只要沾上婚恋焦虑,她们就王者变青铜
  4. ViewState笔记
  5. shapley值法 - 用边际收益衡量每个人的贡献
  6. [Ext JS6]多类型设备开发
  7. 远程服务器返回错误 (411) 所需的长度。
  8. 用SIR模型处理新冠疫情
  9. 网络爬虫设计中需要注意的几个问题
  10. PPT计算机原理结构初步,测量实践初步(赖丽娟).ppt
  11. 通过SQL语句数据库简繁体转换
  12. Linux开启root用户
  13. 有限域(2)——理想和商环
  14. 车载网络测试 - 车载以太网 - ARP详细解析
  15. 服务器端测试经验分享
  16. gis核密度分析工具_抓取公共服务设施POI后,用GIS进行核密度分析的可视化过程...
  17. 专门画像素图的软件_新世纪像素画设计软件,你值得一试!
  18. 网际协议IP简单总结
  19. meterpreter使用详解
  20. NLS(National Language Support)

热门文章

  1. 开源网络备份软件bacula学习笔记
  2. ssh时出现 Agent admitted failure to sign using the key
  3. 如何建立顺畅的项目流程
  4. win10软件拒绝访问删不掉_进程拒绝访问怎么结束_win10关闭进程拒绝访问的处理方法...
  5. Python基础知识详解
  6. 为什么Python是2021最值得学的编程语言?
  7. mvn 默认scope_maven scope 的作用
  8. android 联系人编辑界面,android – 以编程方式编辑联系人的姓名/电话号码
  9. 在云中进行灾难恢复的五种有效方式
  10. Mysql 主从延时监控(pt-heartbeat)详解