webflux中websocket使用

實現(xiàn)方式

在spring中使用websocket有多種方式:

  1. 在spring mvc中使用,這種不做介紹
  2. 在webflux中使用,這是咱們本次要介紹的內(nèi)容
  3. 直接使用spring + netty做websocket,可以見spring+netty

實現(xiàn)步驟

  1. 引入相應(yīng)webflux包
  2. 實現(xiàn)自定義的請求處理類WebSocketHandler
  3. 配置url映射關(guān)系及WebSocketHandlerAdapter
  4. 通過頁面進行測試

MyWebSocketHandler: 對請求進行處理。這個地方有以下注意事項

  • 在真實環(huán)境中,需要進行校驗,因此需要帶參數(shù),在此使用簡單的方式,即直接在請求path上帶參數(shù)
  • 消息通過getPayloadAsText()獲取內(nèi)容后,再次獲取則為空
import com.liukun.test.service.TokenService;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.UrlEncoded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.reactive.socket.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class MyWebSocketHandler implements WebSocketHandler {
    @Autowired
    private TokenService tokenService;

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        // 在生產(chǎn)環(huán)境中,需對url中的參數(shù)進行檢驗,如token,不符合要求的連接的直接關(guān)閉
        HandshakeInfo handshakeInfo = session.getHandshakeInfo();
        if (handshakeInfo.getUri().getQuery() == null) {
            return session.close(CloseStatus.REQUIRED_EXTENSION);
        } else {
            // 對參數(shù)進行解析,在些使用的是jetty-util包
            MultiMap<String> values = new MultiMap<String>();
            UrlEncoded.decodeTo(handshakeInfo.getUri().getQuery(), values, "UTF-8");
            String token = values.getString("token");
            boolean isValidate = tokenService.validate(token);
            if (!isValidate) {
                return session.close();
            }
        }
        Flux<WebSocketMessage> output = session.receive()
                .concatMap(mapper -> {
                    String msg = mapper.getPayloadAsText();
                    System.out.println("mapper: " + msg);
                    return Flux.just(msg);
                }).map(value -> {
                    System.out.println("value: " + value);
                    return session.textMessage("Echo " + value);
                });
        return session.send(output);
    }
}

TokenService: 校驗參數(shù),在生產(chǎn)環(huán)境需要對每個連接進行校驗,符合要求的才允許連接。

import org.springframework.stereotype.Service;

@Service
public class TokenService {
 // demo演示,在引只對長度做校驗
    public boolean validate(String token) {
        if (token.length() > 5) {
            return true;
        }
        return false;
    }
}

WebConfig: 配置類,通過Java Config進行配置。

@Configuration
public class WebConfig {

    @Bean
    public MyWebSocketHandler getMyWebsocketHandler() {
        return new MyWebSocketHandler();
    }
    @Bean
    public HandlerMapping handlerMapping() {
      // 對相應(yīng)的URL進行添加處理器
        Map<String, WebSocketHandler> map = new HashMap<>();
        map.put("/hello", getMyWebsocketHandler());

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

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

index.html: 測試代碼,內(nèi)容如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<textarea id="msgBoxs"></textarea><br>
待發(fā)送消息:<input type="text" id="msg"><input type="button" id="sendBtn" onclick="send()" value="發(fā)送">
<script type="application/javascript">
    var msgBoxs = document.getElementById("msgBoxs")
    var msgBox = document.getElementById("msg")
    document.cookie="token2=John Doe";
    var ws = new WebSocket("ws://localhost:9000/hello?token=aabb123&demo=1&userType=0")
    ws.onopen = function (evt) {
        console.log("Connection open ...");
        ws.send("Hello WebSocket!");
    }

    ws.onmessage = function (evt) {
        console.log("Received Message: ", evt.data)
        var msgs = msgBoxs.value
        msgBoxs.innerText = msgs + "\n" + evt.data
        msgBoxs.scrollTop = msgBoxs.scrollHeight;
    }

    ws.onclose = function (evt) {
        console.log("Connect closed.");
    }



    function send() {
        var msg = msgBox.value
        ws.send(msg)
        msgBox.value = ""
    }
</script>
</body>
</html>

直接運行,并輸入消息,點擊發(fā)送,即可見消息經(jīng)服務(wù)端返回


image.png

cors

可以有以下方法使其支持cors:

1.直接使自定義的WebSocketHandler實現(xiàn)CorsConfigurationSource接口,并返回一個CorsConfiguration, 如:

public class MyWebSocketHandler implements WebSocketHandler, CorsConfigurationSource {
    @Override
    public Mono<Void> handle(WebSocketSession session) {
         ...
    }

    @Override
    public CorsConfiguration getCorsConfiguration(ServerWebExchange exchange) {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");
        return configuration;
    }
}

2.可以在SimpleUrlHandler上設(shè)置corsConfigurations屬性。

參考文檔1

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容