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,浏览器显示正常。


相关推荐
竹等寒5 分钟前
Linux-网络安全私房菜(二)
linux·服务器·web安全
早睡冠军候选人17 分钟前
Ansible学习----Ansible Playbook
运维·服务器·学习·云原生·容器·ansible
sulikey17 分钟前
从实验出发深入理解Linux目录权限:r、w、x分别控制什么?能否进入目录到底由谁决定?
linux·运维·服务器·ubuntu·centos
Arva .2 小时前
WebSocket实现网站点赞通知
网络·websocket·网络协议
游戏开发爱好者83 小时前
FTP 抓包分析实战,命令、被动主动模式要点、FTPS 与 SFTP 区别及真机取证流程
运维·服务器·网络·ios·小程序·uni-app·iphone
纸带4 小时前
USB --SETUP --STATUS阶段
linux·服务器·网络
言之。5 小时前
ClickHouse 数据更新策略深度解析:突变操作与最佳实践
服务器·数据库·clickhouse
火星数据-Tina5 小时前
LOL实时数据推送技术揭秘:WebSocket在电竞中的应用
网络·websocket·网络协议
ajassi20006 小时前
开源 Linux 服务器与中间件(三)服务器--Nginx
linux·服务器·开源
wheeldown6 小时前
【Linux】Linux进程间通信:命名管道(FIFO)的模拟实现重要知识点梳理
linux·运维·服务器