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

简介:Netty搭建websocket服务器,postman可以连接,浏览器无法连接,很奇怪,不知道为什么。最后更换端口解决问题,原来端口时6666,把6666改成其他端口就可以了。

过程:

前端代码

后端netty代码相关配置

java 复制代码
//socket端口
		int port = 4848;
		//websocket端口
		int wsPort=6666;
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try{
			//socket通信
			ServerBootstrap bootstrap = new ServerBootstrap();
			//websocket通信
			ServerBootstrap wbsBootstrap=new ServerBootstrap();
			//处理socket信息
			bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
						.childHandler(
							new ChannelInitializer<SocketChannel>(){
								@Override
								protected void initChannel(SocketChannel ch) throws Exception {
									System.out.println("连接ip"+ch.remoteAddress());
									clientContext.put(ch.remoteAddress().getHostString(),ch);
//									ch.writeAndFlush(Unpooled.copiedBuffer(Bytes.HexString2Bytes("a55a000a820000880d0a")));
									System.out.println(ch.remoteAddress()+"xxxxx!");
									//添加一个粘包分包处理器
									ch.pipeline().addLast(new DelimiterBasedFrameDecoder(29, false, 
		                                    Unpooled.wrappedBuffer(new byte[] {(byte)0x0D,(byte)0x0A})
		                                    ));
									//注册handeler
									ch.pipeline().addLast(new MyNettyServerHandler(systemService));
								}							
							}
						).option(ChannelOption.SO_BACKLOG, 1024)
						.childOption(ChannelOption.SO_KEEPALIVE, true);
			
			wbsBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new WebSocketChannelInitializer());
			
			ChannelFuture f = bootstrap.bind(port).sync();
			ChannelFuture wsf = wbsBootstrap.bind(wsPort).sync();
			
			wsf.channel().closeFuture().sync();
			f.channel().closeFuture().sync();

后端webSocketchannelInitializer()的代码:

java 复制代码
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel>{
	@Override
    protected void initChannel(SocketChannel ch) throws Exception {
		System.out.println("连接ws-ip"+ch.remoteAddress());
//        ChannelPipeline pipeline = ch.pipeline();
//        pipeline.addLast(new HttpServerCodec());
//        pipeline.addLast(new ChunkedWriteHandler());
//        //用于将http数据聚合到一起发送一个请求 fullHttpRequest
//        pipeline.addLast(new HttpObjectAggregator(8192));
//        pipeline.addLast(new WebSocketServerProtocolHandler("/"));//传入websocket path
//        pipeline.addLast(new TextWebSocketHandler());//传入websocket path
		// 获取职责链
		ChannelPipeline pipeline = ch.pipeline();
		// 
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(new HttpObjectAggregator(65535));
		//解决跨域问题
		CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
		pipeline.addLast(new CorsHandler(corsConfig));
		
		pipeline.addLast(new ChunkedWriteHandler());
		pipeline.addLast(new WebSocketServerProtocolHandler("/"));
		pipeline.addLast(new TextWebSocketHandler());
    }
}

后端TextWebSocketHandler()的代码:

java 复制代码
public class TextWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		int size = GlobalChannelGroup.channelGroup.size();
		System.out.println("当前微信墙连接数:" + (size == 0 ? 0 : size - 1));
		System.out.println("收到消息:" + msg.text());
		Channel channel = ctx.channel();
//		ctx.writeAndFlush(msg.text());
//		ctx.writeAndFlush(msg);
		ctx.writeAndFlush(new TextWebSocketFrame("nihaohao"));
//		GlobalChannelGroup.channelGroup.forEach(o -> {
//			if (o.localAddress().toString().endsWith("6666")) {
//				o.writeAndFlush(msg.text());
//			} else {
//				TextWebSocketFrame text = new TextWebSocketFrame(o.remoteAddress() + "发送消息:" + msg.text() + "\n");
//				o.writeAndFlush(text);
//			}
//		});

	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		Channel ch = ctx.channel();
		GlobalChannelGroup.channelGroup.add(ch);
//		GlobalChannelGroup.channels.add(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println(ctx.channel().remoteAddress() + ":离开聊天室");
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		Channel ch = ctx.channel();
		GlobalChannelGroup.channels.add(ctx);
		System.out.println(ch.remoteAddress() + ":连接到聊天室");
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		System.out.println("异常");
		GlobalChannelGroup.channels.remove(ctx);
		ctx.close();
	}
}

最终连接效果就是postman可以正常连接,但是浏览器连接不上。结果如下

浏览器显示如下

如果把端口改成8989,浏览器显示正常。


相关推荐
远方 hi3 小时前
linux如何修改密码,要在CentOS 7系统中修改密码
linux·运维·服务器
资讯分享周4 小时前
过年远控家里电脑打游戏,哪款远控软件最好用?
运维·服务器·电脑
chaodaibing4 小时前
记录一次k8s起不来的排查过程
运维·服务器·k8s
mcupro5 小时前
提供一种刷新X410内部EMMC存储器的方法
linux·运维·服务器
黑客老李5 小时前
区块链 智能合约安全 | 回滚攻击
服务器·数据仓库·hive·hadoop·区块链·php·智能合约
不知 不知6 小时前
最新-CentOS 7 基于1 Panel面板安装 JumpServer 堡垒机
linux·运维·服务器·centos
BUG 4046 小时前
Linux--运维
linux·运维·服务器
九月十九7 小时前
AviatorScript用法
java·服务器·前端
ICT系统集成阿祥8 小时前
科普篇 | “机架、塔式、刀片”三类服务器对比
运维·服务器
progrmmmm8 小时前
k8s使用nfs持久卷
linux·服务器·kubernetes·k8s·运维开发