网络编程复习(六):Netty入门Demo

关于Netty,可以看做是对JDK的nio API的封装,提供了更简单的实现,同时性能,功能更加丰富以及相对应的安全机制,对于Netty的学习,大家可以访问如下网址,里面讲解的很详细,这里仅写一个小demo作为入门。

学习网址:http://ifeve.com/netty5-user-guide/

server:

package 网络编程_Netty;

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

public class Server {
	private int port;
	public Server(int port){
		this.port = port;
	}
	public void run() throws Exception{
		/*定义两个处理IO操作的多线程时间循环器,boss一般用来接受客户端连接,workers用来处理已经被接
		收的连接,这里使用NIOEvent处理tcp协议,还有很多种实现类用于处理不同的传输协议。
		*/
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup workers = new NioEventLoopGroup();
		try {
			//ServerBootstrap是服务端的启动NIO服务的辅助类,用于设置一些服务的参数
			ServerBootstrap bootstrap = new ServerBootstrap();
			//将两个事件循环器加入到辅助类中
			bootstrap.group(boss, workers)
					//指定具体的通道连接方式
					 .channel(NioServerSocketChannel.class)
					 //使用childHandler指定具体的事件处理类
					 .childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new ServerHandler());
						}
					 })
					 //关闭BACKLOG参数作用需要了解TCP底层三次握手机制,底部维持了2个队列,当两个队列和大于BACKLOG时,服务端会拒绝客户端连接
					 .option(ChannelOption.SO_BACKLOG, 128)
					 //保持存活状态
					 .childOption(ChannelOption.SO_KEEPALIVE, true);
			ChannelFuture f = bootstrap.bind(port).sync();//绑定端口
			f.channel().closeFuture().sync();//相当于阻塞
		} finally {
			workers.shutdownGracefully();//关闭操作
			boss.shutdownGracefully();
		}
	}
	public static void main(String[] args) throws Exception{
		new Server(8888).run();
	}
}

serverHandler处理类:

package 网络编程_Netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
 * 处理器类,处理器是由netty生成用来处理IO事件的
 * @author lihao
 *
 */
public class ServerHandler extends ChannelHandlerAdapter{

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

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			ByteBuf buf = (ByteBuf)msg;
			byte[] bys = new byte[buf.readableBytes()];
			buf.readBytes(bys);
			String accept = new String(bys,"utf-8");
			System.out.println(accept);
			String response = new String("你好,服务器已经接受到你的请求");
			ChannelFuture writeAndFlush = ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));//wirte的时候会手动的释放msg
			writeAndFlush.addListener(ChannelFutureListener.CLOSE);//监听写数据进程,当数据写出完毕关闭连接
	}

	
}
client:

package 网络编程_Netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
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 Client {
	public static void main(String[] args) throws Exception {
		EventLoopGroup workers = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.group(workers)
				 .channel(NioSocketChannel.class)
				 .handler(new ChannelInitializer<SocketChannel>() {
					@Override
					protected void initChannel(SocketChannel ch) throws Exception {
						ch.pipeline().addLast(new ClientHandler());
					}
				});
				ChannelFuture f = bootstrap.connect("127.0.0.1",8888).sync();
				f.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty".getBytes()));
				f.channel().closeFuture().sync();
				workers.shutdownGracefully();
	}
}
clientHandler事件处理类

package 网络编程_Netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends ChannelHandlerAdapter{

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

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		
		try {
			ByteBuf buf = (ByteBuf)msg;
			byte[] bys = new byte[buf.readableBytes()];
			buf.readBytes(bys);
			String accept = new String(bys,"utf-8");
			System.out.println(accept);
		} finally {
			ReferenceCountUtil.release(msg);
		}
		
	}

	
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值