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

相关推荐
火云代理30 分钟前
更换网络后为什么会退出登录?分清 IP、Cookie 与会话的关系
服务器·网络·网络协议·tcp/ip·php·ip
xbzb3 小时前
容器 IP 每次重建都变?docker network 五种模式与自定义网桥固定地址
网络·docker·容器·ip·network·固定
火云代理4 小时前
同一个网站,有的网络能打开、有的打不开?认识 IPv4 与 IPv6 的访问差异
服务器·网络·网络协议·tcp/ip·测试工具·php·状态模式
坤坤子吖5 小时前
Linux网络编程:TCP 粘包与半包问题,如何正确处理 TCP 流式数据?
linux·服务器·网络·笔记·网络协议·学习
yuyuxun15 小时前
协同过滤的校园二手物品智能推荐系统的设计与实现 毕业设计-附源码40082
javascript·vue.js·spring boot·python·数据分析·django·课程设计
火云代理8 小时前
Python 使用代理 IP 前,先弄清 Requests 的配置来源与验证方法
网络·python·网络协议·tcp/ip·ip
如夏倾城8 小时前
QUIC——HTTP/3 的唯一底层传输协议 及 0-RTT恢复
网络·网络协议·tcp/ip·安全·http
LGL6030A9 小时前
Java学习历程31——初识Spring Boot
java·spring boot·学习
科研邪修法9 小时前
培训PDF保护配置:把需求转换成可验收权限
linux·服务器·网络
阿达和自己10 小时前
springboot学习-springboot引入MyBatis-Plus
spring boot·学习·mybatis