spring-boot-starter-websocket 客户端 服务端 例子

1. 添加依赖

首先,在pom.xml中添加spring-boot-starter-websocket依赖,正如你已经指出的:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

2. 创建WebSocket配置

创建一个配置类来启用和配置WebSocket。

java 复制代码
import org.springframework.context.annotation.Configuration
import org.springframework.web.socket.config.annotation.EnableWebSocket
import org.springframework.web.socket.config.annotation.WebSocketConfigurer
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry


@Configuration
@EnableWebSocket
open class WebSocketConfig : WebSocketConfigurer {
    override fun registerWebSocketHandlers(registry: WebSocketHandlerRegistry) {
        registry.addHandler(EchoWebSocketHandler(), "/echo")
    }
}

3. 创建WebSocket处理器

创建一个WebSocketHandler来处理消息。

java 复制代码
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class EchoWebSocketHandler extends TextWebSocketHandler {
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // Echo the received message back
        session.sendMessage(message);
    }
}

4. 启动Spring Boot应用程序

创建Application.java来启动应用程序。

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }

}

5. 创建WebSocket客户端

这里是一个简单的WebSocket客户端示例,使用标准Java WebSocket API。

java 复制代码
import jakarta.websocket.ClientEndpoint
import jakarta.websocket.ContainerProvider
import jakarta.websocket.OnMessage
import jakarta.websocket.Session
import java.net.URI


@ClientEndpoint
class EchoClient {
    @OnMessage
    fun onMessage(message: String, session: Session?) {
        println("Received from server: $message")
    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            try {
                val container = ContainerProvider.getWebSocketContainer()
                val uri = "ws://localhost:8080/echo"
                val session: Session = container.connectToServer(EchoClient::class.java, URI.create(uri))
                session.getBasicRemote().sendText("Hello, echo!")
                Thread.sleep(1000) 
                session.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

启动并测试

启动Spring Boot应用程序,然后运行客户端。客户端会发送一条消息到服务器,服务器应该会把相同的消息回传给客户端。

相关推荐
极客先躯18 小时前
高可用巡检脚本实战:一键掌握服务、网络、VIP、资源状态
运维·网络·金融
计算机学姐18 小时前
基于微信小程序的垃圾分类管理系统【2026最新】
java·vue.js·spring boot·mysql·微信小程序·小程序·mybatis
i学长的猫18 小时前
Spring Boot 布隆过滤器最佳实践指南
spring boot·后端·哈希算法
Mr_hwt_12318 小时前
spring boot框架中本地缓存@Cacheable原理与踩坑点详细解析
java·spring boot·后端·缓存
时空潮汐18 小时前
无需公网 IP:神卓 K900 实现海康摄像头异地观看的两种简单方法
服务器·网络·tcp/ip·海康摄像头·神卓n600·神卓云监控
zl97989919 小时前
SpringBoot-自动配置原理
java·spring boot·spring
zx_zx_12319 小时前
传输层协议 tcp
服务器·网络·tcp/ip
Allen Roson19 小时前
Burp Suite抓包软件使用说明1-Http history
网络·网络协议·http
爱吃芒果的蘑菇19 小时前
C++之WebSocket初体验
网络·c++·websocket·网络协议
武昌库里写JAVA20 小时前
C语言 #pragma once - C语言零基础入门教程
vue.js·spring boot·sql·layui·课程设计