最简单明了的springboot整合websocket

前言

  • WebSocket 是一种网络通信协议。RFC6455 定义了它的通信标准。

  • WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

  • HTTP 协议是一种无状态的、无连接的、单向的应用层协议。它采用了请求/响应模型。通信请求只能由客户端发起,服务端对请求做出应答处理。

  • 这种通信模型有一个弊端:HTTP 协议无法实现服务器主动向客户端发起消息。

  • 这种单向请求的特点,注定了如果服务器有连续的状态变化,客户端要获知就非常麻烦。大多数 Web 应用程序将通过频繁的异步 AJAX 请求实现长轮询。轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP 连接始终打开)。


http协议:
http协议
websocket协议:
websocket协议

  • 弄清楚http协议与websocket协议的区别后,接下来我们就开始在springboot的项目中搭建websocket的环境

1.引入websocket的依赖

  • 在pom.xml中引入websocket的依赖
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2.注册配置类

  • 创建WebSocketConfig配置类
@Configuration
public class WebSocketConfig {

    @Bean
    //注入ServerEndpointExporter bean对象,自动注册使用了@ServerEndpoint注解的bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.消息处理类

  • 创建消息处理类,实现客户端与服务端的信息交互
@ServerEndpoint(value = "/chat/{token}")
@Component
public class WebSocketHandler {

    //用来存储每一个客户端对象对应的ChatEndpoint对象
    private static Map<String, WebSocketHandler> onlineUsers = new ConcurrentHashMap<>();

    //用户的token
    private String token;


    @OnOpen
    //连接建立时被调用
    public void onOpen(Session session, EndpointConfig config, @PathParam("token") String token) {
        this.token = token;
        System.out.println("token:"+token);
        System.out.println("连接成功~~~");
    }


    @OnMessage
    //接收到客户端发送的数据时被调用
    public void onMessage(String message, Session session) {
        String id = session.getId();
        System.out.println(id);
        System.out.println("客户端发过来的消息:" + message);
        System.out.println("将信息推送给服务端");
        // 在这里根据接收到的消息进行处理


        // 发送消息给客户端
        sendMessageToClient(session, "我一直与你同在!!!!!哈哈哈哈哈哈哈哈哈哈");
    }

    @OnClose
    //连接关闭时被调用
    public void onClose(Session session) {
        System.out.println("连接关闭");
    }

    // 发送消息给指定客户端
    private void sendMessageToClient(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4.前端测试js

  • 简单的测试客户端与服务端js文件
var ws = new WebSocket('ws://127.0.0.1:9123/clientApi/watchOrder/token');//url:自己配置的url
// 获取连接状态
console.log('ws连接状态:' + ws.readyState);
//监听是否连接成功
ws.onopen = function () {
    console.log('ws连接状态open:' + ws.readyState);
    //连接成功则发送一个数据
    ws.send('test1');
}
// 接听服务器发回的信息并处理展示
ws.onmessage = function (data) {
    console.log('接收到来自服务器的消息:');
    console.log(data);
    //完成通信后关闭WebSocket连接
    ws.close();
}
// 监听连接关闭事件
ws.onclose = function () {
    // 监听整个过程中websocket的状态
    console.log('ws连接状态close:' + ws.readyState);
}
// 监听并处理error事件
ws.onerror = function (error) {
    console.log(error);
}

5.使用百度的控制台发js

  • 没有专用工具的小伙伴可以用浏览器中的控制台进行测试,简单方便嘎嘎好用

客户端给服务端发信息
服务端显示:
服务端与客户端建立链接
至此,一个最简单的springboot整合websocket就搭建完成了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现Spring Boot整合WebSocket,你需要进行以下步骤: 1. 首先,在pom.xml文件中添加WebSocket的相关依赖。可以使用以下两个依赖之一: - 从中提到的依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` - 从中提到的依赖: ```xml <!--webSocket--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket配置类,这个类负责配置WebSocket的相关信息。你可以按照以下方式创建一个配置类[3]: ```java package com.loit.park.common.websocket; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } ``` 3. 至此,你已经完成了WebSocket整合配置。现在,你可以在你的应用中创建WebSocket的控制器并定义你的WebSocket端点。你可以根据你的需求来实现WebSocket端点的业务逻辑。 这就是Spring Boot整合WebSocket的基本步骤。通过这种方式,你可以在Spring Boot应用中轻松地使用WebSocket进行实时通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [springboot整合websocket](https://blog.csdn.net/weixin_45390688/article/details/120448778)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [springboot整合websocket(详解、教程、代码)](https://blog.csdn.net/hjq_ku/article/details/127503180)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Java潜力股

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

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

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

打赏作者

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

抵扣说明:

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

余额充值