我是否使用了正确的方法来使用WebSocket发送ping帧

emeijp43  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(195)

我使用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);


这些都不能工作。我应该做些什么来使它工作?我错过了什么吗?

w8f9ii69

w8f9ii691#

您可以创建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();
    }

字符串

相关问题