Bootstrap

springboot使用websocket

一、概述

1、简介

简介略,附上官方文档,spring5和spring6的官方文档内容大致是一样的:
https://docs.spring.io/spring-framework/docs/5.2.25.RELEASE/spring-framework-reference/web.html#websocket
https://docs.spring.io/spring-framework/reference/6.1/web/websocket.html

二、 使用

1、引包

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

2、配置处理器

创建WebSocket服务器可以实现WebSocketHandler或者,更有可能的是,扩展TextWebSocketHandler或者BinaryWebSocketHandler。以下示例使用TextWebSocketHandler

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.concurrent.CopyOnWriteArrayList;

public class MyHandler extends TextWebSocketHandler {

    // 可以定义一个存储所有session的容器
    private final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 建立请求
        sessions.add(session);
        System.out.println("Connection established: " + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 收到消息
        String payload = message.getPayload();
        System.out.println("Received message: " + payload);
        // 发送回复消息
        for (WebSocketSession s : sessions) {
            s.sendMessage(new TextMessage("Server received: " + payload));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 关闭链接
        sessions.remove(session);
        System.out.println("Connection closed: " + session.getId());
    }

}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

	/**
	 * 将前面的WebSocket处理程序映射到特定的URL
	 */
	@Override
	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(myHandler(), "/myHandler")
				//.addInterceptors(new HttpSessionHandshakeInterceptor()) // 可以拦截session属性
				.setAllowedOrigins("*"); // 跨域
		;
	}

	@Bean
	public WebSocketHandler myHandler() {
		return new MyHandler();
	}

}

3、前端测试

测试地址:https://tool.gitapp.cn/websocket/

连接ws://127.0.0.1:8080/myHandler,发送消息进行测试一下。

使用起来非常的方便

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;