首页 > 解决方案 > Spring Web Flux Websocket在数据接收到现有资源后推送

问题描述

package org.springframework.webflux.websocket.webfluxwebsocketdemo;

import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;

import reactor.core.publisher.Flux;

@SpringBootApplication
@RestController
public class WebFluxWebSocketDemoApplication {

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

    @GetMapping(path = "/pushData")
    public void getRemoteStreaming( @RequestParam("message") String message ) throws URISyntaxException {



    }


    @Bean
    public HandlerMapping webSocketMapping() {
        Map<String, WebSocketHandler> map = new HashMap<>();

        map.put("/echo", session -> session.send(
            Flux.<String>generate(sink -> sink.next(String.format("{ message: 'got local message', date: '%s' }", new Date())))
                .delayElements(Duration.ofSeconds(1)).map(session::textMessage)));

        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setUrlMap(map);
        mapping.setOrder(1);
        return mapping;
    }

    @Bean
    public WebSocketHandlerAdapter handlerAdapter() {
        return new WebSocketHandlerAdapter();
    }

}

上面的代码将每秒向 websocket 客户端发送消息“{ message: 'got local message', date: 'Tue Oct 02 11:34:17 IST 2018' }”

但是,每当我从“pushData”资源接收到数据时,我们如何发送消息,然后我必须将其传递给 websocket 客户端。

标签: websocketspring-webflux

解决方案


推荐阅读