新建springboot maven工程,引入以下包

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>
新建WebSocket配置类
  1. package com.example.demo.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.WebSocketHandler;
  5. import org.springframework.web.socket.config.annotation.EnableWebSocket;
  6. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
  7. import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
  8. /**
  9. * Created by dingshuo on 2017/5/18.
  10. */
  11. @Configuration
  12. @EnableWebSocket
  13. public class WebsocketConfig implements WebSocketConfigurer{
  14. @Override
  15. public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
  16. webSocketHandlerRegistry.addHandler(myHandler(),"/ws").setAllowedOrigins("*").withSockJS();
  17. }
  18. @Bean
  19. public WebSocketHandler myHandler(){
  20. return new com.example.demo.config.WebSocketHandler();
  21. }
  22. }
根据配置类中的Handler定义,进行具体代码编写
  1. package com.example.demo.config;
  2. import org.springframework.stereotype.Component;
  3. import org.springframework.web.socket.CloseStatus;
  4. import org.springframework.web.socket.TextMessage;
  5. import org.springframework.web.socket.WebSocketMessage;
  6. import org.springframework.web.socket.WebSocketSession;
  7. import org.springframework.web.socket.handler.TextWebSocketHandler;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.UUID;
  11. /**
  12. * Created by dingshuo on 2017/5/18.
  13. */
  14. @Component
  15. public class WebSocketHandler extends TextWebSocketHandler{
  16. public static final Map<Object, WebSocketSession> userSocketSessionMap;
  17. static {
  18. userSocketSessionMap = new HashMap<Object, WebSocketSession>();
  19. }
  20. @Override
  21. public void afterConnectionEstablished(WebSocketSession session) throws Exception {
  22. userSocketSessionMap.put(UUID.randomUUID(),session);
  23. System.out.println("建立连接完成");
  24. }
  25. @Override
  26. public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
  27. switch (message.getPayload().toString()){
  28. case "1":
  29. sendMsg(session,new TextMessage("A"));
  30. break;
  31. case "2":
  32. sendMsg(session,new TextMessage("B"));
  33. break;
  34. }
  35. System.out.println("处理消息");
  36. }
  37. @Override
  38. public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
  39. System.out.println("处理消息传出错误");
  40. }
  41. @Override
  42. public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
  43. System.out.println("处理连接关闭");
  44. }
  45. private void sendMsg(WebSocketSession session,TextMessage message) throws Exception {
  46. for (int i=0;i<100;i++){
  47. Thread.sleep(1000);
  48. session.sendMessage(message);
  49. }
  50. }
  51. }
在Handler里可以看出每个连接的连接-接收消息-关闭连接等过程,只需要在相应的函数中完成具体方法即可
此处简单模拟,客户端连接后,发送一个连接字符,然后服务器根据连接字符不断的推送消息(这里是发送“1”或“2”)

新建一个测试用的html静态页面(这里引用了sockjs),代码是抄网上的。。。
注意修改url地址信息
  1. <!doctype html>
  2. <html>
  3. <head>
  4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  5. <script src="http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"></script>
  6. <style>
  7. .box {
  8. width: 300px;
  9. float: left;
  10. margin: 0 20px 0 20px;
  11. }
  12. .box div, .box input {
  13. border: 1px solid;
  14. -moz-border-radius: 4px;
  15. border-radius: 4px;
  16. width: 100%;
  17. padding: 0px;
  18. margin: 5px;
  19. }
  20. .box div {
  21. border-color: grey;
  22. height: 300px;
  23. overflow: auto;
  24. }
  25. .box input {
  26. height: 30px;
  27. }
  28. h1 {
  29. margin-left: 30px;
  30. }
  31. body {
  32. background-color: #F0F0F0;
  33. font-family: "Arial";
  34. }
  35. </style>
  36. </head>
  37. <body lang="en">
  38. <h1>Index</h1>
  39. <div id="first" class="box">
  40. <div></div>
  41. <form><input autocomplete="off" value="Type here..."></input></form>
  42. </div>
  43. <script>
  44. var sockjs_url = 'http://127.0.0.1:8080/ws';
  45. var sockjs = new SockJS(sockjs_url);
  46. $('#first input').focus();
  47. var div = $('#first div');
  48. var inp = $('#first input');
  49. var form = $('#first form');
  50. var print = function(m, p) {
  51. p = (p === undefined) ? '' : JSON.stringify(p);
  52. div.append($("<code>").text(m + ' ' + p));
  53. div.append($("<br>"));
  54. div.scrollTop(div.scrollTop()+10000);
  55. };
  56. sockjs.onopen = function() {print('[*] open', sockjs.protocol);};
  57. sockjs.onmessage = function(e) {print('[.] message', e.data);};
  58. sockjs.onclose = function() {print('[*] close');};
  59. form.submit(function() {
  60. print('[ ] sending', inp.val());
  61. sockjs.send(inp.val());
  62. inp.val('');
  63. return false;
  64. });
  65. </script>
  66. </body>
  67. </html>

Springboot-webscoket with sockjs的更多相关文章

  1. springboot实现服务器端消息推送(websocket + sockjs + stomp)

    服务器端推送技术在web开发中比较常用,可能早期很多人的解决方案是采用ajax向服务器轮询消息,这种方式的轮询频率不好控制,所以大大增加了服务器的压力,后来有了下面的方案:当客户端向服务器发送请求时, ...

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

    springboot+websocket+sockjs进行消息推送[基于STOMP协议] WebSocket是在HTML5基础上单个TCP连接上进行全双工通讯的协议,只要浏览器和服务器进行一次握手,就 ...

  3. 通过springBoot集成搭建webScoket服务器

    前言: 最近工作中有一个需求,就是服务端要主动推送消息给客户端,而我们平常的Http请求只能一请求一响应,为此学习了webScokset通讯技术,以下介绍的是java 通过SpringBoot集成we ...

  4. Springboot + Websocket + Sockjs + Stomp + Vue + Iview 实现java后端日志显示在前端web页面上

    话不多说,看代码. 一.pom.xml 引入spring boot websocket依赖 <dependency> <groupId>org.springframework. ...

  5. webscoket实战之利用httpsession定向推送

    webscoket实战之利用httpsession定向推送 开发框架 springboot 场景 在利用websocket主动推送信息给客户端的过程中,经常会遇到一个普遍需求,就是推送的消息要定向推送 ...

  6. springboot情操陶冶-web配置(四)

    承接前文springboot情操陶冶-web配置(三),本文将在DispatcherServlet应用的基础上谈下websocket的使用 websocket websocket的简单了解可见维基百科 ...

  7. 基于springboot+bootstrap+mysql+redis搭建一套完整的权限架构【六】【引入bootstrap前端框架】

    https://blog.csdn.net/linzhefeng89/article/details/78752658 基于springboot+bootstrap+mysql+redis搭建一套完整 ...

  8. springboot+websocket 归纳收集

    websocket是h5后的技术,主要实现是一个长连接跟tomcat的comet技术差不多,但websocket是基于web协议的,有更广泛的支持.当然,在处理高并发的情况下,可以结合tomcat的a ...

  9. springboot websocket 一篇足够了

    什么是WebSocket WebSocket是一种在单个TCP连接上进行全双工通信的协议 … 为什么要实现握手监控管理 如果说,连接随意创建,不管的话,会存在错误,broken pipe 表面看单纯报 ...

  10. 全栈开发——动手打造属于自己的直播间(Vue+SpringBoot+Nginx)

    前言 大学的学习时光临近尾声,感叹时光匆匆,三年一晃而过.同学们都忙着找工作,我也在这里抛一份简历吧,欢迎各位老板和猎手诚邀.我们进入正题.直播行业是当前火热的行业,谁都想从中分得一杯羹,直播养活了一 ...

随机推荐

  1. 前端框架中 “类mixin” 模式的思考

    "类 mixin" 指的是 Vue 中的 mixin,Regular 中的 implement 使用 Mixin 的目的 首先我们需要知道为什么会有 mixin 的存在? 为了扩展 ...

  2. Vue源码探究-虚拟DOM的渲染

    Vue源码探究-虚拟DOM的渲染 在虚拟节点的实现一篇中,除了知道了 VNode 类的实现之外,还简要地整理了一下DOM渲染的路径.在这一篇中,主要来分析一下两条路径的具体实现代码. 按照创建 Vue ...

  3. C++之自定义key类型,重载操作符

    #include <map>#include <string>using namespace std;class MyString{ public:MyString(){m_s ...

  4. 计算机网络3.2&3.3(第二节介质&第三节多路复用)

    有限的传播介质 双绞线 双绞线电缆 双绞线总结 2 同轴电缆 粗细电缆的传输距离 现在基本都用双绞线和光线 同轴电缆用于居民小区和家庭使用 3 光纤 光纤中以光信号的形式进行传播 正如我们现在看到这样 ...

  5. TensorFlow3学习笔记1

    1.简单实例:向量相加 下面我们通过两个向量相加的简单例子来看一下Tensorflow的基本用法. [1. 1. 1. 1.] + [2. 2. 2. 2.] = [3. 3. 3. 3.] impo ...

  6. linux 下 自己写的 html文件产生中文乱码问题 解决办法

    再文件顶部加上  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" / ...

  7. jquery on事件

    可以给后添加的动态元素绑定事件

  8. margin负边距的使用(超简单)

    写在开头: 在css的世界中,一切都是框,所有的框都处于流动的状态 margin负边距可以使文档流发生偏移   在没有设置margin-bottom的时候,parent的高度会跟随child的内部元素 ...

  9. lavarel box 地址

    https://atlas.hashicorp.com/laravel/boxes/homestead download URL https://atlas.hashicorp.com/laravel ...

  10. 线段树动态开点+树链剖分BZOJ4999

    以每个一个颜色开一颗线段树,内部以dfs序作为线段树节点,权值代表出现次数,维护线段树区间和 #include<iostream> #include<stdio.h> #inc ...