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


相关推荐
2301_8010670923 分钟前
如何通过修改hosts文件、启动Apache服务器、修改httpd.conf文件、配置虚拟主机、创建站点目录和文件等步骤来配置虚拟主机并发布PHP站点
服务器·php·apache
阿湯哥44 分钟前
ES的预置分词器
linux·服务器·elasticsearch
开开心心就好1 小时前
能一站式搞定远程操作需求的实用工具
java·服务器·python·spring·pdf·电脑·软件
wanhengidc1 小时前
物理服务器的作用都有哪些?
运维·服务器
独行soc4 小时前
2025年渗透测试面试题总结-字某跳动-安全研究实习生(三面)(题目+回答)
linux·服务器·安全·web安全·面试·职场和发展
爱吃烤鸡翅的酸菜鱼5 小时前
Java【网络原理】(3)网络编程续
java·运维·服务器·网络
daizikui5 小时前
LVS+Nginx接入层架构图
服务器·nginx·lvs
饭九钦vlog10 小时前
机器人匹诺曹机制,真话假话平衡机制
服务器·经验分享·新浪微博
kyle~11 小时前
linux根目录
linux·服务器
QuiteCoder11 小时前
【Linux】软硬连接与动静态库
linux·运维·服务器