史上最简单的spring-boot集成websocket的实现方式

在应用程序中你只需要几行代码就可以快速的构建websocket服务

简介

在应用程序中你只需要几行代码就可以快速的构建websocket服务,对的这个就是我编写websocket-spring-boot-starter的初衷,主要是写传统的websocket的实现方式感觉每次写起来都好麻烦,又找不到一个好的websocketspring-boot集成的starter,那这样就自己写一个来用,大家在使用中遇到的BUG或者需求欢迎大家到https://github.com/lazyboyl/websocket-spring-boot-starter上提issue。

要求

  • jdk版本为1.8或1.8+
  • spring-boot版本为2.0.1.RELEASE+
  • netty版本为4.1.42.Final

example例子

基于vue的前后端分离的实现的例子

快速开始

1、添加依赖:
     <dependency>
         <groupId>com.github.lazyboyl</groupId>
         <artifactId>websocket-spring-boot-starter</artifactId>
         <version>1.0.3.RELEASE</version>
     </dependency>
2、添加注解

在spring boot的启动类上加上@EnableWebSocketServer注解,并在该注解上设置好需要扫描的路径。

@SpringBootApplication
@EnableWebSocketServer(webSocketScanPackage = {"com.vue.demo.vue"})
public class VueDemoApplication {

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

}
3、编写第一个后端响应请求

你可以像写springMvc一样写websocket,完全不用像以前一样要做各种的配置和处理。

/**
 * @author linzf
 * @since 2020/7/15
 * 类描述: 第一个请求类
 */
@WebSocketController
@WebSocketRequestMapping("/user/")
public class UserController {
    
    /**
     * 这个userService就是我们平时在spring里面写的service
     */
    @Autowired
    private UserService userService;

    /**
     * 功能描述: 模拟字段请求的方式来实现根据用户ID来获取用户数据
     *
     * @param userId 用户的流水ID
     * @return
     */
    @WebSocketRequestMapping("getUserVoByUserId")
    public UserVo getUserVoByUserId(String userId) {
        return userService.getUserVoByUserId(userId);
    }

}
4、编写第一个拦截器

只需要实现WebsocketSecurity接口即可,level方法主要用于界定这个过滤器的执行的顺序,数字越大则级别越高,执行的排序也越高,authentication返回的值若为true则放行,反之则直接被拦截不再往下响应

/**
 * @author linzf
 * @since 2020/7/14
 * 类描述:请求拦截器
 */
public class WebsocketSecurityImpl implements WebsocketSecurity {

    /**
    * 这个authService就是我们平时在spring里面写的service
    **/
    @Autowired
    private AuthService authService;

    @Override
    public int level() {
        return 10;
    }

    @Override
    public Boolean authentication(ChannelHandlerContext ctx, SocketRequest socketRequest) {
        Boolean isPass = authService.authUrl(socketRequest.getUrl());
        System.out.println("----我在这里做了一个模拟的鉴权过程---");
        if(!isPass){
            ctx.channel().writeAndFlush(new TextWebSocketFrame(JsonUtils.objToJson(new SocketResponse(HttpResponseStatus.UNAUTHORIZED.code(), "授权不通过!"))));
        }
        return isPass;
    }
}
4、编写第一个监听器

只需实现WebSocketHandlerListenter接口即可,level方法主要用于界定这个监听器的执行的顺序,数字越大则级别越高,执行的排序也越高,channelInactive当通道关闭的时候执行的方法,handleShake当websocket尝试握手的时候执行的方法。

/**
 * @author linzf
 * @since 2020/7/14
 * 类描述: 通道关闭监听器
 */
public class WebSocketHandlerListenterImpl implements WebSocketHandlerListenter {

    /**
    * 这个webSocketCloseService就是我们平时在spring里面写的service
    **/
    @Autowired
    private WebSocketCloseService webSocketCloseService;


    @Override
    public int level() {
        return 0;
    }

    /**
     * 功能描述: 当浏览器端的通道关闭的时候的响应处理方法
     *
     * @param ctx 当前的通道对象
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("当前关闭的通道的id是:" + ctx.channel().id().asLongText());
        webSocketCloseService.removeChannel(ctx.channel().id().asLongText());
    }

    @Override
    public void handleShake(ChannelHandlerContext ctx) {
        System.out.println("当前开启的通道的id是:" + ctx.channel().id().asLongText());
    }
}
5、编写第一个前端响应请求

前端采用的是vue响应的方式,不过本质上还是用的是浏览器的本身自带的websocket因此写法上没什么差别,只是此处在与后端进行websocket交互的
时候需要按照一定的格式往后端提交数据,格式如下:

  {'url': 后端的请求地址, 'params': 请求的JSON数据}

例如本例中写了一个后端请求的地址是/user/getUserVoByUserId那我们此处的请求地址就是这个地址,同时后端的这个方法的入参是userId,那么我们这边的params的JSON数据
的格式就是{'userId':'123'}那么最终我们请求上来的数据格式如下:

  {'url': '/user/getUserVoByUserId', 'params': {'userId':'123'}}

最后直接调用我们的websocket对象的send方法请求后端即可。

6、编写前端的实现
<template>
<div>
  <button @click="getUserVoByUserId">getUserVoByUserId</button>
</div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      websock: null,
      wsuri: 'ws://127.0.0.1:8399/wsVue'
    }
  },
  created () {
    this.initWebSocket()
  },
  methods: {
    getUserVoByUserId () {
      let actions = {'url': '/user/getUserVoByUserId/', 'params': {'userId': 'abc'}}
      this.websocketsend(JSON.stringify(actions))
    },
    initWebSocket () { // 初始化weosocket
      this.websock = new WebSocket(this.wsuri)
      this.websock.onmessage = this.websocketonmessage
      this.websock.onopen = this.websocketonopen
      this.websock.onerror = this.websocketonerror
      this.websock.onclose = this.websocketclose
    },
    websocketonopen () { // 连接建立之后执行send方法发送数据
    },
    websocketonerror () { // 连接建立失败重连
      console.log('--出错了-')
      this.initWebSocket()
    },
    websocketonmessage (e) { // 数据接收
      const redata = JSON.parse(e.data)
      console.log('后端发送过来的信息是:' + e.data)
    },
    websocketsend (Data) { // 数据发送
      if(this.websock.readyState === 1){
        this.websock.send(Data)
      } else {
        setTimeout(()=>{
          this.websock = new WebSocket(this.wsuri)
          this.websock.onmessage = this.websocketonmessage
          this.websock.onopen = this.websocketonopen
          this.websock.onerror = this.websocketonerror
          this.websock.onclose = this.websocketclose
          setTimeout(()=>{this.websocketsend(Data)},1000)
        },1000)
      }
    },
    websocketclose (e) { // 关闭
      console.log('断开连接', e)
    }
  }
}
</script>

配置

属性默认值说明
websocket.port8399websocket的端口号
websocket.thread.boss12boss的线程数
websocket.thread.work12工作线程数
websocket.actionwswebsocket的响应的地址

通过application.yml 进行配置

websocket:
   port: 8399
   action: ws
   thread:
        boss: 12
        work: 12

版本更新

1.0.3.RELEASE
  • 【发布失败】由于1.0.2发布失败,因此补发1.03版本。
1.0.2.RELEASE
  • 【BUG修复】修复netty与tomcat集成部署时,由于netty的启动导致tomcat启动失败。
1.0.1.RELEASE
  • @WebSocketController注解的类支持构造方法的方式注入的支持。
  • 新增@WebSocketRequestParam支持入参的自定义。
  • 3
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论
Spring-Boot WebSocket 可以实现向日葵远程控制。向日葵是一款远程控制软件,可以让我们在远程控制设备时更加方便和灵活。在使用Spring-Boot实现WebSocket时,我们可以结合向日葵的API来达到远程控制的目的。 首先,在Spring-Boot中,我们需要引入WebSocket的依赖。可以在pom.xml文件中添加相应的依赖,例如: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 然后,我们需要创建WebSocket的配置类。在配置类中,我们可以定义WebSocket的相关设置,例如消息处理器、握手拦截器等。可以参考以下代码: ``` @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "/myHandler").withSockJS(); } @Bean public WebSocketHandler myHandler() { return new MyHandler(); } } ``` 在以上代码中,`registerWebSocketHandlers` 方法用来注册WebSocket处理器,并指定了处理路径。`MyHandler` 是自定义的消息处理器,可以在其中处理接收到的消息、发送消息等。 接下来,我们可以在处理器中调用向日葵的API,实现远程控制的功能。例如: ``` public class MyHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { // 处理接收到的消息 String receivedMessage = message.getPayload(); // 调用向日葵API,实现远程控制 // 发送消息 String responseMessage = "远程控制成功"; session.sendMessage(new TextMessage(responseMessage)); } } ``` 在以上代码中,`handleTextMessage` 方法用来处理接收到的消息。我们可以在其中调用向日葵的API实现远程控制的逻辑,并将结果作为消息发送回客户端。 最后,在Spring-Boot的主类中添加 `@EnableWebSocket` 注解,启用WebSocket功能。 综上所述,通过Spring-Boot WebSocket,我们可以便捷地实现向日葵远程控制的功能。使用WebSocket协议进行通信,同时结合向日葵的API,可以让我们更加灵活地远程控制设备。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

笨_鸟_不_会_飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值