Springboot-webscoket with sockjs

新建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>





posted @ 2017-05-18 15:47  二刀  阅读(1073)  评论(0编辑  收藏  举报