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应用程序,然后运行客户端。客户端会发送一条消息到服务器,服务器应该会把相同的消息回传给客户端。

相关推荐
2301_815091013 分钟前
TCP 并发服务器模型:4 种 IO 模型完整梳理
服务器·网络·tcp/ip
斑马13913 分钟前
Linux软件编程学习笔记(十二)——TCP并发服务器模型
java·服务器·网络
学着改变27538 分钟前
2026便携式超声波流量计性能白皮书 户外巡检适用性横评
大数据·网络·人工智能·科技·产品运营·量子计算
rcms152702692181 小时前
Novellus Systems 02-033134-00晶圆底座加热器
网络
马立杰1 小时前
IE241210_路由安全技术(三层安全)
网络·安全
马立杰1 小时前
IE241211_路由安全技术(三层安全)
网络·安全·智能路由器
迪康Defender2 小时前
公用电脑责任追溯难?迪康端点安全一体化管理系统用户模式详解
java·运维·开发语言·网络·其他·安全
迪康Defender2 小时前
迪康端点安全一体化管理系统文档安全:构建企业文档资产全链路防护体系
运维·网络·安全·web安全·终端安全管理
AI备忘录2 小时前
(十九)华为华三锐捷迈普思科 交换机链路聚合配置命令(LACP/静态聚合五厂商对照)
运维·服务器·网络·网络协议·tcp/ip·华为
raindayinrain2 小时前
理解网络--Tcp性能优化
网络·tcp/ip·性能优化