Netty傻瓜教程(二):客户端问服务器,现在几点钟?

第一节说的例子太简单,实际情况当中我们要对消息进行处理。现在我们来写一个时间服务器。时间服务器的TimeServer文件和第一节里面差不多,改几个类名就可以了,我们只要看下时间服务器的handler。在链接建立以后,服务器向客户端发送系统时间,这个时间是32比特的整数,发送完毕之后就关闭服务器,而不用一直保持读取状态,所以在这里我们在Handler里面不能够使用channelRead()方法,而是使用channelActive()方法。

package com.hengzecn.NettyClient;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TimeClientHandler extends ChannelInboundHandlerAdapter {
	private ByteBuf buf;
	
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		buf = ctx.alloc().buffer(4);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		buf.release();
		buf = null;
	}

	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
		ByteBuf m = (ByteBuf) msg;
		buf.writeBytes(m);
		m.release();
		
		if(buf.readableBytes() >= 4){
			long currentTimeMillis = (buf.readUnsignedInt() - 2208988800L) * 1000L;
			System.out.println(new Date(currentTimeMillis));
			ctx.close();
		}
//		try {
//			long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
//			System.out.println(new Date(currentTimeMillis));
//			ctx.close();
//		} finally{
//			m.release();
//		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		cause.printStackTrace();
		ctx.close();
	}
	
	

}
  1. 就像我们说的那样,channelActive()方法在链接建立后调用,然后传输数据。
  2. 我们在这里使用ByteBuf,至少有4个字节。
  3. ChannelHandlerContext.writeAndFlush()方法返回一个ChannelFuture,它表示未发生的I/O操作,因为Netty是异步的,所以我们只有侦听到ChannelFuture完结以后才去关闭这个Channel。
  4. ChannelFutureListener就是我们实现的侦听类。

我们用Netty来写个客户端测试下:

package com.hengzecn.NettyClient;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class TimeClient {
	public static void main(String[] args) throws Exception{
		String host = "127.0.0.1";
		int port = 8080;
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try{
			Bootstrap b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.handler(new ChannelInitializer<SocketChannel>(){
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new TimeClientHandler());
				}
			});
			
			ChannelFuture f = b.connect(host, port).sync();
			
			f.channel().closeFuture().sync();
		} finally {
			workerGroup.shutdownGracefully();
		}
	}

}
  1. 我们在客户端使用Bootstrap,而不是ServerBootstrap。
  2. 只需要声明一个EventLoopGroup,客户端不使用boss group。
  3. 我们在客户端使用NioSocketChannel。
  4. 客户端的SocketChannel没有父类,因此没有childOption()。
  5. 我们在客户端调用connect()。

客户端的Handler使用channelRead来读取服务器端发来的信息:

package com.hengzecn.NettyClient;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class TimeClientHandler extends ChannelInboundHandlerAdapter {
	private ByteBuf buf;
	
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		buf = ctx.alloc().buffer(4);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		buf.release();
		buf = null;
	}

	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
		ByteBuf m = (ByteBuf) msg;
		buf.writeBytes(m);
		m.release();
		
		if(buf.readableBytes() >= 4){
			long currentTimeMillis = (buf.readUnsignedInt() - 2208988800L) * 1000L;
			System.out.println(new Date(currentTimeMillis));
			ctx.close();
		}
//		try {
//			long currentTimeMillis = (m.readUnsignedInt() - 2208988800L) * 1000L;
//			System.out.println(new Date(currentTimeMillis));
//			ctx.close();
//		} finally{
//			m.release();
//		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
		cause.printStackTrace();
		ctx.close();
	}
	
	

}
  1. 在TCP/IP中,Netty将读取的信息写入ByteBuf。

 

运行客户端,成功收到了服务器发来的时间信息,收到信息后服务就关闭了,如下图所示:

转载于:https://my.oschina.net/u/438393/blog/843722

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值