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

相关推荐
Fnetlink18 分钟前
Fnet 云网安 260807
服务器·网络·人工智能·安全·网络安全
XR12345678816 分钟前
学校图书馆网络改造,方案谁更优?
网络·数据库·php
Boop_wu1 小时前
SpringBoot 集成阿里云短信认证服务(个人)
spring boot·后端·阿里云
宵时待雨1 小时前
linux笔记归纳14:Socket编程TCP
linux·服务器·网络·笔记·tcp/ip
逐米时代2 小时前
工厂数字化规划:BIM与仿真让方案可验证
大数据·网络·人工智能
小蒜学长2 小时前
“守望自然”招募志愿者环保行动网站的设计与实现(代码+数据库+LW)
java·数据库·spring boot·后端
caimouse2 小时前
Winsock 用户态库 (ws2_32.dll) 详细分析
网络
云边云科技_云网融合3 小时前
工业制造多厂区、供应链远程数据传输网络如何优化?
运维·服务器·网络
clear sky .3 小时前
[TCP]MCU上如何编辑TCP服务端程序,思路框架
服务器·网络·tcp/ip
FungLeo3 小时前
Flutter 带 TTL 的多级缓存设计:内存+磁盘+网络三层实战
网络·flutter·缓存·性能优化