Netty使用WebSocket传输文本过大报错

458 阅读1分钟

使用情况1:

请参数WebSocketServerHandshakerFactory 的构造器最后一个参数来控制大小

这个只是一段代码,webSocket链接前的一次http请求 为了来进行链接操作
//如果HTTP解码失败,返回HTTP异常
private void handlerHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) {
    if (!req.getDecoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
        return;
    }

    //构造握手响应返回,本机测试
    WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
            "ws://localhost:7008/websocket", null, false,1024*1024*3);

    handshaker = wsFactory.newHandshaker(req);
    if (handshaker == null) {
        WebSocketServerHandshakerFactory.sendUnsupportedWebSocketVersionResponse(ctx.channel());
    } else {
        handshaker.handshake(ctx.channel(), req);
    }
}

使用情况2:

这种如果需要使用的话,请确认Netty版本

注意:两个导入方式选择一种即可 
要大于等于
<dependency>
    <groupId>org.kgusarov</groupId>
    <artifactId>spring-boot-netty</artifactId>
    <version>2.1.0</version>
</dependency>

或者大于等于
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.45.Final</version>
</dependency>

在管道内就可以使用这种操作方式来进行链接
pipeline.addLast(new WebSocketServerProtocolHandler("/webSocket",null,false,1024*1024*5));