【问题标题】:How do I write an error to a WebSocket channel in Netty?如何将错误写入 Netty 中的 WebSocket 通道?
【发布时间】:2023-03-10 05:15:01
【问题描述】:

我有一个 Netty 4.0.19 应用程序,我在其中使用 TextWebSocketFrames 发送和接收消息。

这些消息在被接收时,都会通过“onmessage”事件处理程序触发。

如何在 onerror 处理程序上生成错误消息?

例如,如何将以下错误条件作为错误而不是消息发送回 Web 套接字客户端?

public void channelRead0(final ChannelHandlerContext ctx, final TextWebSocketFrame msg) throws Exception
{
    final String message = msg.retain().text();

    Envelope envelope = null;
    boolean errorFree = true;

    try
    {
        envelope = EnvelopeJsonEncoder.decode(MessageType.PUBLISH, message).build();
    }
    catch (final Exception e)
    {
        errorFree = false;
        final WebSocketFrame outFrame = new CloseWebSocketFrame(1002, "Closing due to error");
        ctx.writeAndFlush(outFrame);
    }

    if (errorFree)
    {
        ctx.fireChannelRead(envelope);
    }
}

【问题讨论】:

    标签: java websocket netty


    【解决方案1】:

    通常您会编写一个 CloseWebSocketFrame 并指定正确的关闭代码和原因。

    【讨论】:

    • 我编辑了代码以使用 CloseWebSocketFrame,它关闭了套接字,但没有传递“Closing”语句。现在客户端中的 onerror 或 onmessage 都不会触发...?
    猜你喜欢
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多