首页 新闻 会员 周边 捐助

Netty搭建websocket服务器,postman可以连接,浏览器无法连接

0
悬赏园豆:200 [待解决问题]

netty配置如下:

@Slf4j
@Component
public class NettyServer implements CommandLineRunner {

    String WEBSOCKET_URI = "/device_room";

    @Override
    public void run(String... args) throws Exception {
        this.startServer();
    }

    public void startServer() throws Exception {
        EventLoopGroup boosGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            bootstrap.group(boosGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //设置保持活动连接状态
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    //使用匿名内部类的形式初始化通道对象
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //给pipeline管道设置处理器
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new WebSocketServerCompressionHandler());// WebSocket消息压缩处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            pipeline.addLast(new QueryParamExtractorHandler());// 参数校验
                            pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_URI, null,
                                    true, 65535, true, true));// 添加WebSocket握手处理器
                            pipeline.addLast(new IdleStateHandler(10, 0, 0));// 监控读超时事件
                            pipeline.addLast(new HeartbeatHandler());
                            pipeline.addLast(new PubMessageHandler());
                        }
                    });//给workerGroup的EventLoop对应的管道设置处理器
            log.info("netty服务端启动...");
            //绑定端口号,启动服务端
            ChannelFuture channelFuture = bootstrap.bind(6666).sync();
            //对关闭通道进行监听
            channelFuture.channel().closeFuture().sync();
        }
        finally {
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
wzkris的主页 wzkris | 初学一级 | 园豆:4
提问于:2024-06-06 11:29
< >
分享
所有回答(5)
0

127.0.0.1 localhost有时候是会抽风的
要不用正常IP试试

PasteSpider | 园豆:208 (菜鸟二级) | 2024-06-06 14:24
0
[秦时明月] | 园豆:738 (小虾三级) | 2024-06-06 14:44
0

用本地地址试试看,用前端代买试一下localhost

书昀 | 园豆:1072 (小虾三级) | 2024-06-06 16:48
0

是端口号6666的问题,切换到其他端口号则正常

wzkris | 园豆:4 (初学一级) | 2024-06-11 08:06
0

你的ws并没有暴漏在公网,使用内网穿透工具测一下

景伟·郭 | 园豆:152 (初学一级) | 2024-06-13 15:34
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册