如何在未指定子协议时拒绝WebSocket连接

时间:2018-06-15 13:20:45

标签: java spring websocket protocols spring-websocket

当客户端尝试建立WebSocket连接时,我试图只允许特定的子协议。

我的理解是我需要定义一个支持特定子协议的处理程序。

public class MyWebSocketHandler implements WebSocketHandler {
    private static final List<String> subProtocols = Collections.unmodifiableList(Arrays.asList(
        "MySubProtocol_v0",
        "MySubProtocol_v1"
    ));

    @Override
    public List<String> getSubProtocols() {
        return subProtocols;
    }

    @Override
    public Mono<Void> handle(WebSocketSession session) {
        return session.send(session.receive()
            .log((String) null, Level.INFO, true)
            .map(msg -> session.textMessage("Echo: " + msg.getPayloadAsText())));
    }
}

实际上,当我尝试连接并协商任何指定的子协议时,它会通过:

15:11:11 command: /connect ws://localhost:8080/ingest MySubProtocol_v1
15:11:11 system:  Connecting to ws://localhost:8080/ingest
                  Accepted protocols: MySubProtocol_v1
15:11:12 system:  Connection established.
                  Selected protocol: MySubProtocol_v1

当我尝试连接并协商不支持的协议时,未建立连接:

15:14:10 command: /connect ws://localhost:8080/ingest MySubProtocol_v2
15:14:10 system:  Connecting to ws://localhost:8080/ingest
                  Accepted protocols: MySubProtocol_v2
15:14:10 error:   WebSocket error.
15:14:10 system:  Connection closed.
Close status:     1006 (Abnormal Closure)

但是,当我不尝试协商子协议时,建立连接。

15:17:23 command: /connect ws://localhost:8080/ingest
15:17:23 system:  Connecting to ws://localhost:8080/ingest
                  No protocol negotiation.
15:17:23 system:  Connection established.

强制指定正确的子协议需要做些什么?

1 个答案:

答案 0 :(得分:1)

您可以从HandshakeInfo对象获取子协议信息:session.getHandshakeInfo()HandshakeInfo实例包含协商时使用的子协议。