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


相关推荐
繁星¹⁸⁹⁵2 小时前
通过update-alternatives可以实现cuda的多版本切换
服务器
开航母的李大4 小时前
软件系统运维常见问题
运维·服务器·系统架构·运维开发
phoenix09818 小时前
Linux入门DAY27
linux·运维·服务器
xw59 小时前
免费的个人网站托管-PinMe篇
服务器·前端
egoist202311 小时前
【Linux仓库】进程创建与进程终止【进程·柒】
linux·运维·服务器·进程创建·写时拷贝·进程终止
大锦终11 小时前
【Linux】文件系统
linux·服务器·c++
Kyln.Wu11 小时前
【python实用小脚本-190】Python一键删除PDF任意页:输入页码秒出干净文件——再也不用在线裁剪排队
服务器·python·pdf
枫叶丹412 小时前
【Qt开发】常用控件(五)
服务器·前端·qt
励志五个月成为嵌入式糕手13 小时前
0819 使用IP多路复用实现TCP并发服务器
java·服务器·tcp/ip
华纳云IDC服务商14 小时前
服务器Linux防火墙怎样实现访问控制
linux·运维·服务器