第一个Netty程序——编写Echo客户端

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yikong2yuxuan/article/details/80556726

Echo客户端:

①连接到服务器

②发送一个或多个消息

③对于每个消息,等待病接收从服务器返回的相同的消息

④关闭客户端

通过ChannelHandler实现客户逻辑

package netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
@Sharable //标记该类的实例可以被多个Channel共享
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
	
	
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//当被通知Channel是活跃的时候,发送一条消息
		ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks", CharsetUtil.UTF_8));
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		System.out.println("Client received:"+ msg.toString(CharsetUtil.UTF_8));
	}

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

引导客户端

package netty.client;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
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 EchoClient {
	private final String host;
	private final int port;
	
	public EchoClient(String host,int port) {
		this.host = host;
		this.port = port;
	}
	
	public void start() throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			//创建Bootstrap
			Bootstrap b = new Bootstrap();
			//指定EventLoopGroup已处理客户端事件;需要适用于NIO的实现
			b.group(group)
				//适用于NIO传输的Channel类型
				.channel(NioSocketChannel.class)
				//设置服务器的InetSocketAddress
				.remoteAddress(new InetSocketAddress(host,port))
				//在创建Channel时,向ChannelPipeline中添加一个EchoClientHandler实例
				.handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new EchoClientHandler());
					}
				});
			//连接到远程节点,阻塞等待直到连接完成
			ChannelFuture f = b.connect().sync();
			//阻塞直到Channel关闭
			f.channel().closeFuture().sync();
		}finally {
			//关闭线程池并且释放所有的资源
			group.shutdownGracefully().sync();
		}
	}
	
	public static void main(String[] args) throws Exception {
		if(args.length != 2) {
			System.err.println("Usage:"+EchoClient.class.getSimpleName()+"<host><port>");
			return;
		}
		String host = args[0];
		int port = Integer.parseInt(args[1]);
		new EchoClient(host,port).start();
	}
}

猜你喜欢

转载自blog.csdn.net/yikong2yuxuan/article/details/80556726