热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

详解springboot实现websocket

这篇文章主要介绍了详解springboot实现websocket,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

前言

QQ这类即时通讯工具多数是以桌面应用的方式存在。在没有websocket出现之前,如果开发一个网页版的即时通讯应用,则需要定时刷新页面或定时调用ajax请求,这无疑会加大服务器的负载和增加了客户端的流量。而websocket的出现,则完美的解决了这些问题。

spring boot对websocket进行了封装,这对实现一个websocket网页即时通讯应用来说,变得非常简单。

 一、准备工作

pom.xml引入


  org.springframework.boot
  spring-boot-starter-websocket

完整的pom.xml文件代码如下:

<&#63;xml version="1.0" encoding="UTF-8"&#63;>

  4.0.0

  com.example
  spring-boot-16
  0.0.1-SNAPSHOT
  jar

  spring-boot-16
  Demo project for Spring Boot

  
    org.springframework.boot
    spring-boot-starter-parent
    1.5.3.RELEASE
     
  

  
    UTF-8
    UTF-8
    1.8
  

  
    
      org.springframework.boot
      spring-boot-starter-thymeleaf
    
    
      org.springframework.boot
      spring-boot-starter-web
    
    
      org.springframework.boot
      spring-boot-starter-websocket
    

    
      org.springframework.boot
      spring-boot-devtools
      runtime
    
    
      org.springframework.boot
      spring-boot-starter-test
      test
    

  

  
    
      
        org.springframework.boot
        spring-boot-maven-plugin
      
    
  




二、代码编写

1.创建名为“WebSocketConfig.java”的类来配置websocket,并继承抽象类“AbstractWebSocketMessageBrokerConfigurer”

此类声明“@EnableWebSocketMessageBroker”的注解

package com.example;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

  @Override
  public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic");
    config.setApplicationDestinationPrefixes("/app");
  }

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/my-websocket").withSockJS();
  }

}

这里配置了以“/app”开头的websocket请求url。和名为“my-websocket”的endpoint(端点)

 2.编写一个DTO类来承载消息:

package com.example;

public class SocketMessage {

  public String message;

  public String date;

}

3.创建App.java类,用于启用spring boot和用于接收、发送消息的控制器。

package com.example;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
@EnableScheduling
@SpringBootApplication
public class App {

  public static void main(String[] args) {
    SpringApplication.run(App.class, args);
  }

  @Autowired
  private SimpMessagingTemplate messagingTemplate;

  @GetMapping("/")
  public String index() {
    return "index";
  }

  @MessageMapping("/send")
  @SendTo("/topic/send")
  public SocketMessage send(SocketMessage message) throws Exception {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    message.date = df.format(new Date());
    return message;
  }

  @Scheduled(fixedRate = 1000)
  @SendTo("/topic/callback")
  public Object callback() throws Exception {
    // 发现消息
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    messagingTemplate.convertAndSend("/topic/callback", df.format(new Date()));
    return "callback";
  }
}

“send”方法用于接收客户端发送过来的websocket请求。

@EnableScheduling注解为:启用spring boot的定时任务,这与“callback”方法相呼应,用于每隔1秒推送服务器端的时间。

 4.在“resources/templates”目录下创建index.html文件:





三、运行效果

点击“连接”按钮,出现发送消息的输入框。并接收到服务器端的时间推送。

输入发送内容并点击“发送”按钮后,页面显示出刚才发送的消息。

点击“断开”按钮,则服务器端不会再推送消息。

总结

在开发一个基于web的即时通讯应用的过程中,我们还需考虑session的机制。

还需要一个集合来承载当前的在线用户,并做一个定时任务,其目的是用轮询的方式定时处理在线用户的状态,有哪些用户在线,又有哪些用户离线。

参考:

http://spring.io/guides/gs/scheduling-tasks/

http://spring.io/guides/gs/messaging-stomp-websocket/

代码地址:https://github.com/carter659/spring-boot-16

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


推荐阅读
author-avatar
勇敢的思竹
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有