使用netty开发简单样例

Server端代码:

EchoServer.java

package com.zhuyun.test;

import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * Netty 服务端代码
 * 
 * @author lihzh
 * @alia OneCoder
 * @blog http://www.coderli.com
 */
public class EchoServer {
	private final int port;
	
	public EchoServer(int port){
		this.port = port;
	}
	
	public void start() throws Exception{
		final EchoServerHandler serverHandler = new EchoServerHandler();
		EventLoopGroup group = new NioEventLoopGroup();	//创建EventLoopGroup
		try{
			ServerBootstrap b = new ServerBootstrap();	//创建ServerBootstrap
			b.group(group)
			.channel(NioServerSocketChannel.class)		//指定使用一个NIO传输Channel
			.localAddress(new InetSocketAddress(port))	//用指定的端口设置socket地址
			.childHandler(new ChannelInitializer<SocketChannel>() {	//在Channel的ChannelPipeline中加入EchoServerHandler
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(serverHandler);//EchoServerHandler是@Sharable的,所以我们可以一直用同一个实例
				}
			});
			ChannelFuture f = b.bind().sync();//异步的绑定服务器,sync()一直等到绑定完成
			f.channel().closeFuture().sync();//获得这个Channel的CloseFuture,阻塞当前线程直到关闭操作完成
		}finally{
			group.shutdownGracefully().sync();//关闭EventLoopGroup,释放所有资源
		}
		
	}

	public static void main(String args[]) throws Exception {
		new EchoServer(12000).start();
	}
}


EchoServerHandler.java

package com.zhuyun.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.util.CharsetUtil;

@Sharable			//表明一个ChannelHandler可以被多个Channel安全的共享
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//每次收到消息时被调用
		ByteBuf in = (ByteBuf) msg;
		System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8));		//把消息打印到控制台
		ctx.write(in);				//将收到的消息写入发送方,不刷新输出消息
	}
	
	@Override						//用来通知handler上一个ChannelRead()是被这批消息中的最后一个消息调用
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		//刷新挂起的数据到远端,然后关闭Channel
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
	}
	
	@Override						//在读操作异常被抛出时被调用
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();			//打印异常堆栈跟踪消息
		ctx.close();						//关闭这个Channel
	}
}




Client端代码:

EchoClient.java

package com.zhuyun.test;

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;

import java.net.InetSocketAddress;

/**
 * Netty 客户端代码
 * 
 * @author lihzh
 * @alia OneCoder
 * @blog http://www.coderli.com
 */
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 b = new Bootstrap();	//创建Bootstrap
			b.group(group)	//指定EventLoopGroup来处理客户端事件;需要EventLoopGroup的NIO实现
			.channel(NioSocketChannel.class)		//用于NIO传输的Channel类型
			.remoteAddress(new InetSocketAddress(host, port))	//设置服务器的InetSocketAddress
			.handler(new ChannelInitializer<SocketChannel>() {	//当一个Channel创建时,把一个EchoClientHandler加入它的pipeline中
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new EchoClientHandler());
				}
			});
			ChannelFuture f = b.connect().sync();			//连接到远端,一直等到连接完成
			f.channel().closeFuture().sync();				//一直阻塞到Channel关闭
		}finally{
			group.shutdownGracefully().sync();				//关闭所有连接池,释放所有资源
		}
		
	}
	
	public static void main(String args[]) throws Exception {
		new EchoClient("localhost", 12000).start();
	}

}

EchoClientHandler.java

package com.zhuyun.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandler.Sharable;
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 {
		//当收到连接成功的通知,发送一条消息
		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();//异常发生时,记录错误日志,关闭Channel
		ctx.close();
	}
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值