使用SpringBoot集成的WebSocket实现长连接

本文介绍了如何在SpringBoot项目中集成WebSocket,包括导入相关依赖,配置WebSocket处理类和拦截器,以及编写WebSocket处理器来管理连接、处理消息。同时,文章还展示了测试连接的步骤,包括浏览器控制台的交互操作。
该文章已生成可运行项目,

SpringBoot+WebSocket

1、导入包

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

2、websocket配置类

实现WebSocketConfigurer接口的类只能生效一个,使用时要避免多个类实现WebSocketConfigurer接口。
实现WebSocketConfigurer接口,实现registerWebSocketHandlers()方法,配置处理类,连接路径,作用域,拦截器等。
将拦截器HandshakeInterceptor 作为内部类写在配置类里,分别是前置拦截和后置拦截,前置拦截一般用于提取请求中的信息,用于验证和区分不同的用户。

package com.hsh.websocketproject.config;

import com.hsh.websocketproject.handler.MyWebSocketHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
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 org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @author hsh
 * @date 2023/7/24 4:11
 */
@Configuration //告诉SpringBoot这是一个配置类,让SpringBoot加载配置
@EnableWebSocket //用于开启注解接收和发送消息
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new MyWebSocketHandler(), "/ws")//设置处理类和连接路径
                .setAllowedOrigins("*") //设置作用域
                .addInterceptors(new MyWebSocketInterceptor());//设置拦截器
    }
    /**
     * 自定义拦截器拦截WebSocket请求
     */
    class MyWebSocketInterceptor implements HandshakeInterceptor {
        //前置拦截一般用来注册用户信息,绑定 WebSocketSession
        @Override
        public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                       WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
            System.out.println("前置拦截~~");
            String userName = "hsh";
            attributes.put("userName", userName);
            return true;
        }

        @Override
        public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Exception exception) {
            System.out.println("后置拦截~~");
        }
    }
}

3、编写处理器类

afterConnectionEstablished :连接成功后调用。
handleMessage :处理发送来的消息。
handleTransportError: 连接出错时调用。
afterConnectionClosed :连接关闭后调用。
supportsPartialMessages :是否支持分片消息。(传输大文件才用得到,一般直接使用return false就可以了)

package com.hsh.websocketproject.handler;

import org.springframework.web.socket.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hsh
 * @date 2023/7/24 4:50
 */
public class MyWebSocketHandler implements WebSocketHandler {
    //所有连接的集合
    private static final Map<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userName = session.getAttributes().get("userName").toString();
        SESSIONS.put(userName, session);
        System.out.println("成功建立连接~ userName: " + userName);
    }


    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String msg = message.getPayload().toString();
        System.out.println(msg);
        String userName = session.getAttributes().get("userName").toString();
        sendMessage(userName,"服务器收到消息收到"+userName+"发送的消息,消息内容为:"+msg);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接出错");
        if (session.isOpen()) {
            session.close();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        String userName = session.getAttributes().get("userName").toString();
        System.out.println(userName + "的连接已关闭,status:" + closeStatus);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    /**
     * 指定发消息
     *
     * @param message
     */
    public static void sendMessage(String userName, String message) {
        WebSocketSession webSocketSession = SESSIONS.get(userName);
        if (webSocketSession == null || !webSocketSession.isOpen()) return;
        try {
            webSocketSession.sendMessage(new TextMessage(message));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     *
     * @param message
     */
    public static void fanoutMessage(String message) {
        SESSIONS.keySet().forEach(us -> sendMessage(us, message));
    }
}


4、测试连接

在浏览器控制台逐条输入

//新建一个WebSocket对象,设置好长连接的地址,并建立链接
ws = new WebSocket("ws://localhost:8800/ws");
//收到服务端信息时把消息打印在控制台
ws.onmessage=function(data){console.log(data)};
//向服务器发送消息
ws.send('向服务器发送的消息!');
//使用结束后,不要忘记关闭长连接
ws.close();

websocket浏览器截图
websocket浏览器截图
websocket服务端截图
websocket服务端截图

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值