我是否使用正确的方法通过 websocket 发送 ping 帧

问题描述 投票:0回答:1

我使用 netty

implementation 'io.netty:netty-all:4.1.65.Final'
作为我的 websocket 服务器,现在我想为应用程序添加心跳。我想做的是从客户端发送 ping 消息,然后从服务器端返回 pong 消息。现在我面临一个问题,服务器端总是将客户端 ping 消息视为纯文本帧,而不是控制帧。这是服务器端代码,如下所示:

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (null != msg && msg instanceof FullHttpRequest) {
        FullHttpRequest request = (FullHttpRequest) msg;
        String uri = request.uri();
        Map paramMap=getUrlParams(uri);
        if(uri.contains("?")){
            String newUri=uri.substring(0,uri.indexOf("?"));
            System.out.println(newUri);
            request.setUri(newUri);
        }
    }else if(msg instanceof TextWebSocketFrame){
        TextWebSocketFrame frame=(TextWebSocketFrame)msg;
    }else if(msg instanceof PingWebSocketFrame){
        PingWebSocketFrame frame=(PingWebSocketFrame)msg;
    }
    super.channelRead(ctx, msg);
}

代码总是遇到

TextWebSocketFrame
,我尝试过从客户端发送 ping 消息,如下所示:

const heartbeatInterval = setInterval(() => {
            if (chatWebsocket && chatWebsocket.readyState === WebSocket.OPEN) {
                const pingFrame = new ArrayBuffer(2);
                const pingView = new DataView(pingFrame);
                pingView.setInt8(0, 0x89);
                pingView.setInt8(1, 0);
                chatWebsocket.send(pingFrame);
            }
        }, HEARTBEAT_INTERVAL_MS);

像这样:

const heartbeatInterval = setInterval(() => {
            if (chatWebsocket && chatWebsocket.readyState === WebSocket.OPEN) {
               
                chatWebsocket.send('Ping');
            }
        }, HEARTBEAT_INTERVAL_MS);

我也尝试过这个:

const heartbeatInterval = setInterval(() => {
            if (chatWebsocket && chatWebsocket.readyState === WebSocket.OPEN) {
                
                chatWebsocket.send('ping');
            }
        }, HEARTBEAT_INTERVAL_MS);

也尝试过这个:

 const heartbeatInterval = setInterval(() => {
                if (chatWebsocket && chatWebsocket.readyState === WebSocket.OPEN) {
                    
                    chatWebsocket.send('');
                }
            }, HEARTBEAT_INTERVAL_MS);

这些都行不通。我应该怎么做才能让它发挥作用?我是不是错过了什么?

typescript websocket netty
1个回答
0
投票

您可以将 Ping 消息创建为 Netty

PingWebSocketFrame
的实例并发送。类似于下面的代码示例。

    /**
     * Send a ping message to the server.
     *
     * @param buf content of the ping message to be sent.
     */
    public void sendPing(ByteBuffer buf) throws InterruptedException {
        if (channel == null) {
            // Handle this.
        }
        channel.writeAndFlush(new PingWebSocketFrame(Unpooled.wrappedBuffer(buf))).sync();
    }
© www.soinside.com 2019 - 2024. All rights reserved.