netty: 将传递数据格式转为String,并使用分隔符发送多条数据

自定义分割符,用:DelimiterBasedFrameDecoder类

ByteBuf转String,用StringDecoder类

参考代码:

//设置连接符/分隔符,换行显示
ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
//DelimiterBasedFrameDecoder:自定义分隔符
sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
				
//设置为字符串形式的解码:将传递的buf改为String
sc.pipeline().addLast(new  StringDecoder());
	
//处理数据			
sc.pipeline().addLast(new ClientHandler());

  

 

完整代码:

client代码

public static void main(String[] args) throws InterruptedException {
		
		EventLoopGroup worker = new NioEventLoopGroup();
		Bootstrap b = new Bootstrap();
		b.group(worker)
		.channel(NioSocketChannel.class)
		.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				// TODO Auto-generated method stub
				//设置连接符/分隔符,换行显示
				ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
				//DelimiterBasedFrameDecoder:自定义分隔符
				sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
				
				//设置为字符串形式的解码:将传递的buf改为String
				sc.pipeline().addLast(new  StringDecoder());
				
				sc.pipeline().addLast(new ClientHandler());
			}
		});
		//连接端口
		ChannelFuture cf = b.connect("127.0.0.1", 8765).sync();
		cf.channel().writeAndFlush(Unpooled.copiedBuffer("aaa$_".getBytes()));
		cf.channel().writeAndFlush(Unpooled.copiedBuffer("bbbbb$_".getBytes()));
		cf.channel().writeAndFlush(Unpooled.copiedBuffer("cccccccc$_".getBytes()));
		
		cf.channel().closeFuture().sync();		
		worker.shutdownGracefully();
		
	}

  

 

clientHandler代码

public class ClientHandler extends ChannelHandlerAdapter {

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
		//super.channelRead(ctx, msg);
		try {
			//在传输的时候已经将ByteBuf转为string
			String str = (String)msg;			
			System.out.println("Client: " + str);
		} finally {
			// TODO: handle finally clause
			ReferenceCountUtil.release(msg);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		cause.printStackTrace();
		ctx.close();
	}

	
}

  

 

Server代码:

public static void main(String[] args) throws InterruptedException {
		
		//待client连接的线程
		EventLoopGroup boss = new NioEventLoopGroup();
		//处理事务的线程
		EventLoopGroup worker = new NioEventLoopGroup();
		//bootstarp辅助类,注册server服务
		ServerBootstrap b = new ServerBootstrap();
		b.group(boss, worker)
		.channel(NioServerSocketChannel.class)
		.option(ChannelOption.SO_BACKLOG, 1024)
		.option(ChannelOption.SO_SNDBUF, 32*1024)
		.option(ChannelOption.SO_RCVBUF, 32*1024)
		.childHandler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel sc) throws Exception {
				// TODO Auto-generated method stub
				//设置连接符,换行显示
				ByteBuf buf = Unpooled.copiedBuffer("$_".getBytes());
				//DelimiterBasedFrameDecoder:自定义分隔符
				sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, buf));
				
				//将buf转string
				sc.pipeline().addLast(new StringDecoder());
				
				sc.pipeline().addLast(new ServerHandler());
			}
		});
		
		//指定监听接口
		ChannelFuture cf = b.bind(8765).sync();		
		cf.channel().closeFuture().sync();
		
		boss.shutdownGracefully();
		worker.shutdownGracefully();
	}

  

ServerHandler代码

public class ServerHandler extends ChannelHandlerAdapter{

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub
		//super.channelRead(ctx, msg);
		//handler设置了buf转String
		String str = (String)msg;
		System.out.println("Serer:" + str);
		
		String response = "我是响应的数据$_";
		ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		//super.exceptionCaught(ctx, cause);
		cause.printStackTrace();
		ctx.close();
	}
}

  

转载于:https://www.cnblogs.com/achengmu/p/10944694.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,可以的。不过在整合Netty和Spring Boot之前,我们需要先了解一下RPC的概念和原理。 RPC,全称为Remote Procedure Call,即远程过程调用。它的作用是让分布式系统中的不同节点之间能够像本地调用一样,通过网络调用远程节点的方法或函数,从而实现节点之间的数据交互和通信。 在RPC中,通常会有一个服务提供者和一个服务消费者。服务提供者会将自己的方法或函数暴露出来,供服务消费者调用。服务消费者则会通过网络向服务提供者发送请求,获取响应结果。 在进行RPC调用时,服务提供者和服务消费者之间需要进行相互校验,以确保双方都是可信的。常用的校验方式包括基于Token的认证和基于SSL的加密通信。 接下来,我们可以通过Netty来实现客户端和服务端之间的通信。具体实现方式如下: 1. 在Spring Boot项目中引入Netty的依赖,例如: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.36.Final</version> </dependency> ``` 2. 实现服务提供者和服务消费者的代码逻辑,在其中包含RPC校验的逻辑。 3. 在服务提供者中,创建Netty的ServerBootstrap对象,并设置相关参数,例如: ```java ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(new NioEventLoopGroup()) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new RpcDecoder(RpcRequest.class), new RpcEncoder(RpcResponse.class), new RpcHandler()); } }); ChannelFuture future = bootstrap.bind().sync(); future.channel().closeFuture().sync(); ``` 其中,RpcDecoder和RpcEncoder用于将RPC请求和响应对象转换为字节数组,RpcHandler用于处理RPC请求,并返回响应结果。 4. 在服务消费者中,创建Netty的Bootstrap对象,并设置相关参数,例如: ```java Bootstrap bootstrap = new Bootstrap(); bootstrap.group(new NioEventLoopGroup()) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(host, port)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new RpcEncoder(RpcRequest.class), new RpcDecoder(RpcResponse.class), new RpcProxyHandler()); } }); RpcProxyHandler rpcProxyHandler = bootstrap.connect().sync().channel().pipeline().get(RpcProxyHandler.class); ``` 其中,RpcProxyHandler用于发送RPC请求,并返回响应结果。 5. 最后,在服务消费者中调用服务提供者的方法即可,例如: ```java HelloService helloService = rpcProxyHandler.create(HelloService.class); String result = helloService.sayHello("world"); ``` 这样,我们就可以通过Spring Boot和Netty实现RPC调用和网络通信了。需要注意的是,在实际应用中,我们还需要考虑并发访问、性能优化、服务治理等方面的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值