e2

滴滴侠,fai抖

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

由于SpringBoot已经整合了WebSocket,使用起来非常方便。这篇博客的前提是已经搭建好SpringBoot项目,如果没有搭建好,请参考http://blog.csdn.net/u010889616/article/details/79561808这篇文章。

项目结构如下:

gradle添加依赖

  1.  
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket
  2.  
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-websocket', version: '2.0.0.RELEASE'

(1)开启WebSocket服务。

新建WebSocketConfig.java类,添加@Configuration注解

 

  1.  
    package com.wzj.demo.websocket;
  2.  
     
  3.  
    import org.springframework.context.annotation.Bean;
  4.  
    import org.springframework.context.annotation.Configuration;
  5.  
    import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  6.  
     
  7.  
    /**
  8.  
    * Created by wzj on 2018/3/14.
  9.  
    */
  10.  
    @Configuration
  11.  
    public class WebSocketConfig
  12.  
    {
  13.  
    @Bean
  14.  
    public ServerEndpointExporter serverEndpointExporter()
  15.  
    {
  16.  
    return new ServerEndpointExporter();
  17.  
    }
  18.  
    }
(2)配置/websocket站点

使用@ServerEndpoint注解来配置/websocket站点,来让前端访问,每一个函数都有注释。

 

  1.  
    package com.wzj.demo.websocket;
  2.  
     
  3.  
    import org.springframework.stereotype.Component;
  4.  
     
  5.  
    import javax.websocket.OnClose;
  6.  
    import javax.websocket.OnMessage;
  7.  
    import javax.websocket.OnOpen;
  8.  
    import javax.websocket.Session;
  9.  
    import javax.websocket.server.ServerEndpoint;
  10.  
    import java.io.IOException;
  11.  
    import java.util.List;
  12.  
    import java.util.concurrent.CopyOnWriteArrayList;
  13.  
     
  14.  
    /**
  15.  
    * Created by wzj on 2018/3/14.
  16.  
    */
  17.  
    @ServerEndpoint(value = "/websocket")
  18.  
    @Component
  19.  
    public class MyWebSocket
  20.  
    {
  21.  
    /**
  22.  
    * 在线人数
  23.  
    */
  24.  
    public static int onlineNumber = 0;
  25.  
     
  26.  
    /**
  27.  
    * 所有的对象
  28.  
    */
  29.  
    public static List<MyWebSocket> webSockets = new CopyOnWriteArrayList<MyWebSocket>();
  30.  
     
  31.  
    /**
  32.  
    * 会话
  33.  
    */
  34.  
    private Session session;
  35.  
     
  36.  
    /**
  37.  
    * 建立连接
  38.  
    *
  39.  
    * @param session
  40.  
    */
  41.  
    @OnOpen
  42.  
    public void onOpen(Session session)
  43.  
    {
  44.  
    onlineNumber++;
  45.  
    webSockets.add(this);
  46.  
     
  47.  
    this.session = session;
  48.  
     
  49.  
    System.out.println("有新连接加入! 当前在线人数" + onlineNumber);
  50.  
    }
  51.  
     
  52.  
    /**
  53.  
    * 连接关闭
  54.  
    */
  55.  
    @OnClose
  56.  
    public void onClose()
  57.  
    {
  58.  
    onlineNumber--;
  59.  
    webSockets.remove(this);
  60.  
    System.out.println("有连接关闭! 当前在线人数" + onlineNumber);
  61.  
    }
  62.  
     
  63.  
    /**
  64.  
    * 收到客户端的消息
  65.  
    *
  66.  
    * @param message 消息
  67.  
    * @param session 会话
  68.  
    */
  69.  
    @OnMessage
  70.  
    public void onMessage(String message, Session session)
  71.  
    {
  72.  
    System.out.println("来自客户端消息:" + message);
  73.  
     
  74.  
    sendMessage("欢迎连接");
  75.  
    }
  76.  
     
  77.  
    /**
  78.  
    * 发送消息
  79.  
    *
  80.  
    * @param message 消息
  81.  
    */
  82.  
    public void sendMessage(String message)
  83.  
    {
  84.  
    try
  85.  
    {
  86.  
    session.getBasicRemote().sendText(message);
  87.  
    }
  88.  
    catch (IOException e)
  89.  
    {
  90.  
    e.printStackTrace();
  91.  
    }
  92.  
    }
  93.  
    }

(3)在webapp/WEB-INF/jsp目录,新建index.jsp文件

webSocket = new WebSocket("ws://localhost:8080/websocket");  //连接本地后台的/websocket服务

webSocket有三个响应事件onopen(服务连通)、onmesage(收到消息)、onclose(连接被关闭)

 

  1.  
    <%--
  2.  
    Created by IntelliJ IDEA.
  3.  
    User: wzj
  4.  
    Date: 2016/10/8
  5.  
    Time: 21:24
  6.  
    To change this template use File | Settings | File Templates.
  7.  
    --%>
  8.  
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9.  
    <html>
  10.  
    <head>
  11.  
    <title>Index</title>
  12.  
    </head>
  13.  
    <body>
  14.  
     
  15.  
    <div>你好</div>
  16.  
    <div id="message"></div>
  17.  
     
  18.  
    <canvas id="canvas" style="border: 1px solid red;"></canvas>
  19.  
    </body>
  20.  
    </html>
  21.  
    <script>
  22.  
     
  23.  
    var webSocket;
  24.  
    if (window.WebSocket)
  25.  
    {
  26.  
    webSocket = new WebSocket("ws://localhost:8080/websocket");
  27.  
     
  28.  
    //连通之后的回调事件
  29.  
    webSocket.onopen = function()
  30.  
    {
  31.  
    webSocket.send("发送数据");
  32.  
    };
  33.  
     
  34.  
    //接收后台服务端的消息
  35.  
    webSocket.onmessage = function (evt)
  36.  
    {
  37.  
    var received_msg = evt.data;
  38.  
    alert("数据已接收:" + received_msg);
  39.  
    };
  40.  
     
  41.  
    //连接关闭的回调事件
  42.  
    webSocket.onclose = function()
  43.  
    {
  44.  
    alert("连接已关闭...");
  45.  
    };
  46.  
     
  47.  
    }
  48.  
     
  49.  
    </script>
  50.  
     

(4)在Controller配置url,来访问index.jsp页面

 

  1.  
    package com.wzj.demo.controller;
  2.  
     
  3.  
    import org.springframework.web.bind.annotation.RequestMapping;
  4.  
    import org.springframework.web.bind.annotation.ResponseBody;
  5.  
    import org.springframework.web.bind.annotation.RestController;
  6.  
    import org.springframework.web.servlet.ModelAndView;
  7.  
     
  8.  
    /**
  9.  
    * Created by wzj on 2018/3/14.
  10.  
    */
  11.  
    @RestController
  12.  
    public class WelcomeController
  13.  
    {
  14.  
    /**
  15.  
    * 首页
  16.  
    * @return 测试
  17.  
    */
  18.  
    @RequestMapping(value = "/welcome")
  19.  
    @ResponseBody
  20.  
    public String welcome()
  21.  
    {
  22.  
    return "Hello World";
  23.  
    }
  24.  
     
  25.  
    @RequestMapping(value = "/index")
  26.  
    public ModelAndView index(ModelAndView view)
  27.  
    {
  28.  
    //设置jsp名字
  29.  
    view.setViewName("index");
  30.  
     
  31.  
    //传递数据
  32.  
    view.addObject("name","张三");
  33.  
     
  34.  
    return view;
  35.  
    }
  36.  
    }

(5)测试

启动SpingBoot,在浏览器输入http://127.0.0.1:8080/index,就会发现日志中打印出,有客户端连接,并收到消息。



在浏览器端也收到消息


Demo Github地址: https://github.com/HelloKittyNII/SpringBoot/tree/master/SpringBootDemo

posted on 2019-09-06 21:03  纯黑Se丶  阅读(582)  评论(0编辑  收藏  举报