学习Netty之Netty客户端服务端Demo(以前写的了,发出来记录)

客户端代码:

public class NettyClient {
	
	
	public static void main(String[] args) {
		NioEventLoopGroup group  = new NioEventLoopGroup();
		try{
			Bootstrap b = new Bootstrap();
		
			b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,Delimiters.lineDelimiter()[0]));
					ch.pipeline().addLast(new StringDecoder());
					ch.pipeline().addLast(new ClientHandler());
					ch.pipeline().addLast(new StringEncoder());
				}
			});
		
			ChannelFuture f = b.connect("localhost", 10007).sync();
			String content  = "张三\r\n";
			
			ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer();
			//将字节数组填充到buf中
			buf.writeBytes(content.getBytes(Charset.defaultCharset()));
			
			f.channel().writeAndFlush(buf);	
			
			
			f.channel().closeFuture().sync();
			Object result = f.channel().attr(AttributeKey.valueOf("key")).get();
			System.out.println(result);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			group.shutdownGracefully();
		}
		
	}
}

服务端代码:

public class NettyServer {
	public void start(){
	//服务端开启2个group,一个用于监听事件(单线程),一个用于处理I/O
		EventLoopGroup parent = new NioEventLoopGroup(1);
		EventLoopGroup child = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(parent, child).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Delimiters.lineDelimiter()[0]));
					ch.pipeline().addLast(new NettyServerHandler());
					ch.pipeline().addLast(new StringEncoder(Charset.defaultCharset()));
				}
			});
			
			ChannelFuture future = b.bind(10007).sync();
			future.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			parent.shutdownGracefully();
			child.shutdownGracefully();
		}
			
	}
	
	public static void main(String[] args) {
		NettyServer n = new NettyServer();
		n.start();
	}
	
}

ClientHandler代码

public class ClientHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		super.channelRegistered(ctx);
		System.out.println("--------------------------------------");
		System.out.println("客户端管道注册完毕"+ctx.channel().toString());
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		super.channelActive(ctx);
		System.out.println("客户端可用");

	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("客户端读取数据");
		ctx.channel().attr(AttributeKey.valueOf("key")).set(msg);
		ctx.channel().close();
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		super.channelUnregistered(ctx);
		System.out.println("客户端管道注销");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelInactive(ctx);
		System.out.println("客户端管道不可用");
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		super.channelReadComplete(ctx);
		System.out.println("客户端管道读取数据完毕");
	}
	
	
	
}

ServerHandler

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		super.channelRegistered(ctx);
		System.out.println("管道注册完毕"+ctx.channel().toString());
	}

	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelUnregistered(ctx);
		System.out.println("管道注销完毕");
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelActive(ctx);
		System.out.println("管道变得可用");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		System.out.println("管道变得不可用");

	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("====================读取数据");
		if(msg instanceof ByteBuf){
			ByteBuf b = (ByteBuf)msg;
			String content = b.toString(Charset.defaultCharset());
			System.out.println(content);
			String s = "李四\r\n";
			ctx.channel().writeAndFlush(s);
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		System.out.println("管道读数据完毕");

	}
}

 

好的,下面是一个简单的 Netty 客户端服务端示例代码,可以相互发送消息: 服务端代码: ```java public class NettyServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 接收客户端的消息 ByteBuf buf = (ByteBuf) msg; String request = buf.toString(CharsetUtil.UTF_8); System.out.println("Client request: " + request); // 向客户端发送响应消息 String response = "Hello, Client!"; ByteBuf respBuf = Unpooled.copiedBuffer(response, CharsetUtil.UTF_8); ctx.writeAndFlush(respBuf); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 客户端代码: ```java public class NettyClientHandler extends ChannelOutboundHandlerAdapter { private ChannelHandlerContext ctx; @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { // 向服务器发送消息 ByteBuf buf = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8); ctx.writeAndFlush(buf); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { // 接收服务端的响应 ByteBuf buf = (ByteBuf) msg; String response = buf.toString(CharsetUtil.UTF_8); System.out.println("Server response: " + response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // 发生异常时关闭连接 cause.printStackTrace(); ctx.close(); } } ``` 启动代码: ```java public class NettyDemo { public static void main(String[] args) throws InterruptedException { // 创建 EventLoopGroup EventLoopGroup group = new NioEventLoopGroup(); try { // 创建 ServerBootstrap ServerBootstrap serverBootstrap = new ServerBootstrap(); // 配置 ServerBootstrap serverBootstrap.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(8888)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyServerHandler()); } }); // 启动服务端 ChannelFuture serverFuture = serverBootstrap.bind().sync(); // 创建 Bootstrap Bootstrap clientBootstrap = new Bootstrap(); // 配置 Bootstrap clientBootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress("localhost", 8888)) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyClientHandler()); } }); // 启动客户端 ChannelFuture clientFuture = clientBootstrap.connect().sync(); // 客户端向服务器发送消息 NettyClientHandler clientHandler = (NettyClientHandler) clientFuture.channel().pipeline().last(); clientHandler.write("Hello, Server!"); // 关闭客户端服务端 clientFuture.channel().closeFuture().sync(); serverFuture.channel().closeFuture().sync(); } finally { // 释放资源 group.shutdownGracefully().sync(); } } } ``` 在上面的代码中,服务端使用 `ChannelInboundHandlerAdapter` 处理客户端的请求,客户端使用 `ChannelOutboundHandlerAdapter` 向服务端发送请求。在启动代码中,先启动服务端,再启动客户端,并使用 `ChannelFuture` 对象获取客户端的 `NettyClientHandler` 对象,通过该对象向服务端发送消息。需要注意的是,客户端服务端都需要使用同一个 `EventLoopGroup`。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值