package com.ssyf.test;

import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.time.Duration;

public class WebFluxWebSocketClientDemo {
    public static void main(String[] args) throws InterruptedException {
        // 1. 创建基于 Netty 的 WebSocket 客户端（异步非阻塞）
        ReactorNettyWebSocketClient client = new ReactorNettyWebSocketClient();

        // 2. 连接服务端并处理消息（响应式编程，Java8 兼容）
        client.execute(
                URI.create("wss://ws.bmiss3.zhubei.cn/?"),
                (WebSocketSession session) -> {
                    System.out.println("已连接至服务端！");
                    // 发送消息给服务端
                    Mono<Void> sendMsg = session.send(
                            Mono.just(session.textMessage("Hello Server! From WebFlux Client"))
                    );
                    // 接收服务端消息
                    Mono<Void> receiveMsg = session.receive()
                            .map(msg -> msg.getPayloadAsText())
                            .doOnNext(payload -> System.out.println("收到服务端消息：" + payload))
                            .then();
                    // 组合发送和接收逻辑
                    return Mono.zip(sendMsg, receiveMsg).then();
                }
        ).block(Duration.ofSeconds(30));
    }
}