新建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. Hdu 1007 最近点对

    题目链接 Quoit Design Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Other ...

  2. Spring_使用(JDBC)

    Spring_对JDBC的支持 使用JdbcTemplate更新数据库 导入jar包 创建applicationcontext.xml <?xml version="1.0" ...

  3. SPSS统计基础-均值功能的使用

    SPSS统计基础-均值功能的使用 均值过程计算一个或多个自变量类别中因变量的子组均值和相关的单变量统计.您也可以获得单因素方差分析.eta 和线性相关检验. 统计量.合计.个案数.均值.中位数.组内中 ...

  4. px和rem换算

    bootstrap默认 html{font-size: 10px;} rem是一个相对大小的值,它相对于根元素<html>, 假设,我们设置html的字体大小的值为html{font-si ...

  5. thinkphp5.0 模板输出常用内容

    1.在模板获取session和cookie等全局变量 {$Think.session.user_id}//输出$_SESSION['user_id']变量 2.获取请求信息 {$Request.con ...

  6. 生成主键ID,唯一键id,分布式ID生成器雪花算法代码实现

    工具类:  package com.ihrm.common.utils; import java.lang.management.ManagementFactory; import java.net. ...

  7. hdu 1950 最长上升子序列(lis) nlogn算法【dp】

    这个博客说的已经很好了.http://blog.csdn.net/shuangde800/article/details/7474903 简单记录一下自己学的: 问题就是求一个数列最长上升子序列的长度 ...

  8. oracle函数 MIN([distinct|all]x)

    [功能]统计数据表选中行x列的最大值. [参数]all表示对所有的值求最大值,distinct只对不同的值求最大值,默认为all 如果有参数distinct或all,需有空格与x(列)隔开. [参数] ...

  9. Android 使用SwipeActionAdapter开源库实现简单列表的左右滑动操作

    我们做listview左右滑动操作时,一般中情况下,都是像QQ那样,左滑弹出操作菜单(删除.编辑),然后选择菜单操作: 这样的效果不可谓不好,算是非常经典. 另外,有少数的APP,尤其是任务管理类的A ...

  10. mysql 表名和字段、备注

    select t1.table_schema ,t1.table_name ,t2.ordinal_position ,t2.column_name ,t2.data_type ,t2.charact ...