SpringBoot整合WebSocket

在这里插入图片描述

一、WebSocket与Http的区别

HTTP是应用层上的一个单向的、无状态的、基于请求与响应的协议。http协议本身是没有持久通信能力的,当客户端向服务器发送HTTP请求时,接收到请求后,服务器会将响应发送给客户端。每个请求都与一个对应的响应相关联,在发送响应后客户端与服务器的连接会被关闭。这种的基于请求响应的通讯方式有一点不足,服务器端无法主动向客户端推送数据。
在这里插入图片描述
Websocket是应用层上的一个全双工的有状态协议。websocket以ws://或wss://开头,它必须依赖 HTTP 协议进行一次握手 ,握手成功后,数据就直接从 TCP 通道传输,与 HTTP 无关了。

与HTTP协议不同,websocket是长连接模式,连接后客户端和服务器之间的连接将保持活动状态,直到被任何一方终止。在通过客户端和服务器中的任何一方关闭连接之后,连接将从两端终止。这种模式的缺点是连接会持续占用服务器资源,可以采用心跳机制检测当前连接是否存在数据传输,如果没有数据传输,先关闭连接以节约服务器资源。
在这里插入图片描述

二、搭建Websocket服务端

1.导入websocket依赖。

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

2.编写websocket配置类。

package com.it.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
@EnableWebSocket // 启用websocket
public class WebSocketConfig {

	@Bean
    public ServerEndpointExporter getServerEndpointExporter() { //服务终端
        return new ServerEndpointExporter();
    }
}

WebSocket是基于事件的方式实现的通讯操作,javax.websocket包下提供了许多事件注解。

No注解作用
1@ServerEndpoint声明一个WebSocket操作终端
1@PathParam接收客户端请求路径参数
1@OnOpen监听WebSocket连接打开事件
1@OnClose监听WebSocket连接关闭事件
1@OnMessage监听WebSocket接收到消息事件
1@OnError监听WebSocket方法出错事件

编写WebSocket处理类。

package com.it.handle;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Component
@ServerEndpoint("/websocket/{token}") // 提供给客户端一个操作终端
public class WebSocketHandler {

    @OnOpen
    public void handleOpen(Session session, @PathParam("token") String token) {
        if (StringUtils.isEmpty(token)) {
            sendMessage(session, "[websocket ERROR] 客户端Token错误,连接失败");
        }
        log.info("[websocket]客户端创建连接,session ID = {} ", session.getId());
    }

    @OnClose
    public void handleClose(Session session) {
        log.info("[websocket]客户端断开websocket连接,session ID = {} ", session.getId());
    }

    @OnError
    public void handleError(Session session, Throwable throwable) {
        log.info("[websocket]出现错误,session ID = {} ", session.getId());
        log.info("[websocket]出现错误,throwable = {} ", throwable);
    }

    @OnMessage
    public void handleMessage(Session session, String message) {
        log.info("[websocket]用户发送请求,session ID = {}, message = {}", session.getId(), message);
        sendMessage(session, "[ECHO]" + message);
    }

    // 发送数据到客户端
    private void sendMessage(Session session, String message) {
        if (Objects.isNull(session)) {
            return;
        }
        synchronized (session) { // 同步发送
            try {
                session.getBasicRemote().sendText(message); // 发送数据
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

三、搭建Websocket客户端

WebSocket默认支持跨域访问,客户端可以搭建在其它项目中(button-classic.css)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket</title>
    <style type="text/css">
        input {
            outline-style: none ;
            border: 1px solid #ccc;
            border-radius: 3px;
            padding: 13px 14px;
            width: 400px;
            font-size: 14px;
            font-weight: 700;
            font-family: "Microsoft soft";
        }
        #echo-div{
            width: 650px;
            height: 300px;
            padding: 20px;
            background-color: #eee;
            margin-top:10px;
        }
    </style>
    <link rel="stylesheet" type="text/css" href="./css/button-classic.css" />
    <script type="text/javascript" >
        window.onload = function() {
            const url = 'ws://localhost:8080/websocket/test-token';
            let websocket = new WebSocket(url);
            websocket.onopen = function(event) {
                document.getElementById('echo-div').innerHTML += '<p>服务器连接成功</p>'
            }
            websocket.onclose = function(event) {
                document.getElementById('echo-div').innerHTML += '<p>服务器连接关闭...</p>'
            }
            websocket.onmessage = function(obj) {
                document.getElementById('echo-div').innerHTML += '<p>' + obj.data + '</p>'
                document.getElementById('message').value = '';
            }
            document.getElementById('send-btn').addEventListener('click', function(e) {
                let message = document.getElementById('message').value;
                websocket.send(message);
            })
            document.getElementById('close-btn').addEventListener('click', function(e) {
                websocket.close();
            })
        }
    </script>
</head>
<body>
<div>
    <span>信息:</span>
    <input id="message" type="text" />
    <button id="send-btn" class="button orange" >发送</button>
    <button id="close-btn" class="button black" >关闭</button>
</div>
<div id="echo-div"></div>
</body>
</html>

启动前端项目,访问编写的websocket页面进行简单测试,websocket通信成功。
在这里插入图片描述
后台日志:
加粗样式

  • 12
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值