Spring Boot下websocket简单示例

前言

本文基于Spring对websocket的集成来实现websocket的简单入门。本文以及后续文章相关技术如下

  1. sockjs
  2. webstomp-client
  3. Spring官网的websocket文档
  4. Spring Boot等

引入websocket依赖

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

请注意:本文基于Spring的web应用,意味着你需要将其他SpringBoot web项目的依赖加入才能正常运行该示例。

定义MyHandler

package com.yyoo.boot.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class MyHandler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 当前消息的访问session
        System.out.println(session);
        // 当前的消息
        System.out.println(message);
        // 给前端发送消息
        session.sendMessage(new TextMessage("你发送的消息我收到了"));
    }
}

我们的MyHandler继承了TextWebSocketHandler,前后消息发送之后会进入该Handler的方法。

除了TextWebSocketHandler,还有BinaryWebSocketHandler等可以使用。不用解释,他们一个处理文本消息,一个处理字节消息。根据自身情况选择即可。

接收到消息之后的实现,示例非常简单,打印两个参数,回复一个消息而已。

配置类MyWebSocketConfigurer

package com.yyoo.boot.websocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import javax.annotation.Resource;

@Configuration
@EnableWebSocket
public class MyWebSocketConfigurer implements WebSocketConfigurer {

    @Resource
    private MyHandler myHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myHandler,"/myHandler")// 将我们定义的Handler配置为websocket处理器
//                .setAllowedOrigins("http://localhost:11111") // 配置跨域,此处不能配置*,需要配置具体的前端地址
                .setAllowedOriginPatterns("*") // 使用该方法才能配置*号,建议生产不要配置为*
                .withSockJS(); // 启动SockJs支持(否则前端无法使用Sockjs进行访问)
    }
}

注:我们的示例只提供了一个handler,你可以根据需要添加更多的handler。

前端测试代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证websocket</title>
</head>
<body>

<script type="text/javascript" src="socket/sockjs.min.js"></script>

<label>输入信息:</label><input id="ms" value=""/>
<br/>
<button onclick="send();">发送</button>
<button onclick="shudown()">关闭</button>

<script>

	// IP和端口是后端SpringBoot应用的对应ip和端口
	// /myspringboot是我后端应用的上下文地址
	// /myHandler是上面的websocket配置的地址
    var sock = new SockJS('http://localhost:8070/myspringboot/myHandler');
    sock.onopen = function() {
        console.log('open');
        sock.send('test');
    };

    sock.onmessage = function(e) {
        console.log('message', e.data);
    };

    sock.onclose = function() {
        console.log('close');
    };

    function send(){
        console.log(document.getElementById("ms").value)
        sock.send(document.getElementById("ms").value);
    }

    function shudown(){
        sock.close();
    }

</script>

</body>
</html>

示例再简单不过,我想不用过多解释了吧

后语

文本只是非常简单的使用了spring提供的websocket API。Spring提供的websocket STOMP支持功能更为强大。支持认证、授权令牌等。后续我们再讨论。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值