netty之helloworld示例

介绍

Netty是基于NIO,实现了对NIO的封装。netty常用来做RPC通信,对于传统的NIO而言,API的使用及其不便,在每次读写后都需要flip()操作才能保证整个字节数组的正确读写,因此Netty作者对此实现了封装,他希望netty用户专注于业务代码,而其余部分交给netty来实现。
关于netty入门的代码在我的github上可以下载。

Netty设计

NIO单线程模型
在这里插入图片描述
NIO线程池模型
在这里插入图片描述
Netty模型
在这里插入图片描述
ChannelHandlerContext:
在这里插入图片描述
netty的操作的基于Future模型,通过callable实现异步。
有了上述几个模型,基本可以模拟Netty实现对NIO的简单封装,目标是将handler和通信部分分离,如有机会,笔者会在后续的博客中模拟Netty实现对NIO的一个简单封装。

helloworld

netty代码诸如一致,其只需要用户编写自己的handler对业务代码进行处理,其余部分大体相同。
服务端

package netty.helloword;

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 {
	public static void main(String[] args) throws InterruptedException {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();

		try{
			ServerBootstrap bootstrap = new ServerBootstrap();				//Server配置器
			bootstrap.group(boss, worker).channel(NioServerSocketChannel.class)		
			.option(ChannelOption.SO_BACKLOG, 1024)			//设置最多等待建立连接数
			.option(ChannelOption.SO_BACKLOG, 32 * 1024)	//设置发送缓冲大小
			.option(ChannelOption.SO_RCVBUF, 32 * 1024)		//设置接收缓冲大小
			.childOption(ChannelOption.SO_KEEPALIVE, true)		//保持连接
			.childHandler(new ChannelInitializer<SocketChannel>() {		//增加监听
				@Override
				protected void initChannel(SocketChannel sc) throws Exception {
					sc.pipeline().addLast(new ServerHandler());			//设置业务处理类
				}
			});

			ChannelFuture cf1 = bootstrap.bind(9999).sync();	//bind()异步返回Future通过sync()同步,参考Future模式
			cf1.channel().closeFuture().sync();					//为了让程序监听,这里需要保持程序运行,相当于一个死循环
		}finally{
			boss.shutdownGracefully();
			worker.shutdownGracefully();			
		}
	}
}

ServerHandler

package netty.helloword;

import java.io.UnsupportedEncodingException;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws UnsupportedEncodingException{
		byte[]req = new byte[msg.readableBytes()];
		msg.readBytes(req);
		String body = new String(req,"utf-8");
		System.out.println("server : " + body);
		
		String response = "Hi Client";
		ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));			//会自动释放Buf
	}
}

Client

package netty.helloword;

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 Client {
	public static void main(String[] args) {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();		//创建客户端配置器
			bootstrap.group(group);						//加入到NIO线程池

			bootstrap.channel(NioSocketChannel.class);
			bootstrap.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new ClientHandler());
				}
			});
			ChannelFuture cf = bootstrap.connect("127.0.0.1",9999).sync();//连接
			cf.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			group.shutdownGracefully();
		}				
	}
}

ClientHandler

package netty.helloword;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public class ClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
	//收到数据时触发
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
			throws Exception {
			byte buf[] = new byte[msg.readableBytes()];
			msg.readBytes(buf);
			System.out.println(new String(buf,"utf-8"));
			ReferenceCountUtil.release(msg);
	}
	
	//通道激活时触发
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(Unpooled.copiedBuffer("hello Server!",CharsetUtil.UTF_8));
	}
	
	//异常直接关闭通道
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();			//打印异常
		ctx.close();
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
       在Java界,Netty无疑是开发网络应用的拿手菜。你不需要太多关注复杂的NIO模型和底层网络的细节,使用其丰富的接口,可以很容易的实现复杂的通讯功能。 本课程准备的十二个实例,按照由简单到复杂的学习路线,让你能够快速学习如何利用Netty来开发网络通信应用。                每个实例简洁、清爽、实用,重点在“用”上,即培训大家如何熟练的使用Netty解决实际问题,抛弃以往边讲应用边分析源码的培训模式所带来的“高不成低不就”情况,在已经能够熟练使用、并且清楚开发流程的基础上再去分析源码就会思路清晰、事半功倍。        本套课程的十二个实例,各自独立,同时又层层递进,每个实例都是针对典型的实际应用场景,学了马上就能应用到实际项目中去。 学习好Netty 总有一个理由给你惊喜!! 一、应用场景        Netty已经众多领域得到大规模应用,这些领域包括:物联网领域、互联网领域、电信领域、大数据领域、游戏行业、企业应用、银行证券金融领域、。。。  二、技术深度        多款开源框架中应用了Netty,如阿里分布式服务框架 Dubbo 的 RPC 框架、淘宝的消息中间件 R0cketMQ、Hadoop 的高性能通信和序列化组件 Avro 的 RPC 框架、开源集群运算框架 Spark、分布式计算框架 Storm、并发应用和分布式应用 Akka、。。。  三、就业前景         很多大厂在招聘高级/资深Java工程师时要求熟练学习、或熟悉Netty,下面只是简要列出,这个名单可以很长。。。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值