springboot使用webSocket推送消息

1.引入依赖
核心是@ServerEndpoint注解,如果使用tomcat发布项目的话,则需要引入javaee依赖.

<dependency>
  <groupId>javax</groupId>
  <artifactId>javaee-api</artifactId>
  <version>7.0</version>
  <scope>provided</scope>

但如果使用sprngboot的内置tomcat时,则不需要引入javaee-api,srping-boot已经包含了。
使用springboot的websocket功能首先引入springboot组件

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-websocket</artifactId>
      <version>1.3.5.RELEASE</version>
  </dependency>

2.使用@ServerEndpoint时要创建websocket endpoint
首先要注入ServerEndpointExporter,这个bean会自动注册使用@ServerEndpoint注解声明的websocket endpoint。
但如果不使用springboot内置的容器,则不需要注入,其会由容器自己提供和管理

@Component
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }

3.用例实现
前端代码

<html>
  <head>
    <meta name="viewport" content="width=device-width"/>
    <title>WebSocket客户端</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
  </head>
  <style>
    body{
      background:url(./images/fengjing.jpg)  no-repeat center center;
      background-size:cover;
      background-attachment:fixed;
      background-color:#CCCCCC;
    }
  </style>
  <body>
    <div style="margin-top: 150px; text-align:center">
      <p><h2><b>WebSocket测试</b></h2></p>
    </div>
    <div class="container" >
      <div class="row clearfix" style="margin-top: 250px">
        <div class="col-md-4 column">
          <button type="button" style="width:150px; height:50px" id="btnConnection" class="btn btn-lg btn-success">连接</button>
        </div>
        <div class="col-md-4 column">
          <button type="button" style="width:150px; height:50px" id="btnSend" class="btn btn-lg btn-info">发送消息</button>
        </div>
        <div class="col-md-4 column">
          <button type="button" style="width:150px; height:50px" id="btnClose" class="btn btn-lg btn-danger">关闭</button>
        </div>
      </div>
    </div>
    <script src="https://cdn.bootcss.com/jquery/1.10.0/jquery.min.js"></script>
    <script>
      var websocket;
      if ('websocket' in window) {
          $('#btnConnection').click(function(){
              //实现WebSocket对象,指定要连接的服务器地址与端口
              websocket = new WebSocket('ws://127.0.0.1:8080/websocketdemo/ws/loooody');
              //打开事件
              websocket.onopen = function(){
                  alert('socket已打开');
              };
              //获得消息事件
              websocket.onmessage = function(msg){
                  alert(msg.data);
              };
              //关闭事件
              websocket.onclose = function(){
                  alert('Socket已关闭');
              };
              //发生了错误事件
              websocket.onerror = function(){
                  alert('发生了错误');
              }
          });
          //发送消息
          $('#btnSend').click(function(){
              websocket.send('这是来自客户端的消息' + '\n地址 : ' +  location.href + '\n日期 :' + new Date());
          });
          //关闭
          $('#btnClose').click(function(){
              websocket.close();
          });
      }else{
          alert("您的浏览器不支持WebSocket");
      }
    </script>
  </body>
</html>

服务端代码

@Component
@ServerEndpoint("/ws/{user}")
public class WebSocketDemo {
    private String currentUser;
    //连接打开时执行
    @OnOpen
    public void onOpen(@PathParam("user") String user, Session session) {
        currentUser = user;
        System.out.println("Connected...." + session.getId());
    }
    //收到消息时执行
    @OnMessage
    public String onMessage(String message, Session session) {
        System.out.println(currentUser + " : " + message);
        return currentUser + " : " + message;
    }
    //连接关闭时执行
    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println(String.format("session %s closed because of %s", session.getId(), closeReason));
    }
    //连接错误时执行
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }
}

4.小结
在使用websocket时遇到不少问题,路径,websocket无法new成功等,所幸已经有很多前辈在这条路上走了很远,凭借他们的经验才爬出一个有一个的大坑。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值