SpringBoot WebSocket 样例

SpringBoot WebSocket 样例

pom.xml依赖配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
    <groupId>javax.websocket</groupId>
    <artifactId>javax.websocket-api</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

TextWebSocketHandler 编写


import org.springframework.lang.NonNull;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.HashMap;
import java.util.Map;

public class KteMessageWebSocketHandler extends TextWebSocketHandler {

	private final Map<String, WebSocketSession> sessions = new HashMap<>();

	public Map<String, WebSocketSession> getSessions() {
		return sessions;
	}

	@Override
	public void afterConnectionEstablished(@NonNull WebSocketSession session) {
		sessions.put(session.getId(), session);
	}
}

WebSocketConfigurer 配置

package com.kte.system.websocket;

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

/**
 * Created by EalenXie on 2022/3/2 14:25
 */
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {


	@Override
	public void registerWebSocketHandlers(@NonNull WebSocketHandlerRegistry registry) {
		registry.addHandler(kteMessageWebSocketHandler(), "/websocket/message").setAllowedOrigins("*");
	}

	@Bean
	public KteMessageWebSocketHandler kteMessageWebSocketHandler() {
		return new KteMessageWebSocketHandler();
	}

}
posted @ 2024-01-10 13:44  EalenXie  阅读(21)  评论(0编辑  收藏  举报