Bootstrap

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

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

过程:
前端代码
在这里插入图片描述
后端netty代码相关配置

//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()的代码:

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()的代码:

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

在这里插入图片描述
在这里插入图片描述

;