netty入门demo

在公司最近用到netty,所以研究了下,写了个demo。

服务端如下:

package smu.gaoyi.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;

/**
 * Netty服务端
 * 
 * @author gaoyi
 *
 */
public class Server {

								
	private void bind(int port) {

		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			//服务端辅助启动类,用以降低服务端的开发复杂度
			ServerBootstrap bootstrap = new ServerBootstrap();
			bootstrap.group(bossGroup, workerGroup)
					//实例化ServerSocketChannel
					.channel(NioServerSocketChannel.class)
					//设置ServerSocketChannel的TCP参数
					.option(ChannelOption.SO_BACKLOG, 1024)
					.childHandler(new ChildChannelHandler());
									
			// ChannelFuture:代表异步I/O的结果
			ChannelFuture f = bootstrap.bind(port).sync();			
			f.channel().closeFuture().sync();
			
			
			
			
		} catch (InterruptedException e) {
			System.out.println("启动netty服务异常");
			e.printStackTrace();
		} finally {
			workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
		}
			
	}
	
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

		@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			//handler
			ch.pipeline().addLast(new ServerHandler());
		}
		
	}

	public static void main(String[] args) {
		int port = 8888;
		new Server().bind(port);
		
	}

}

服务端的handler:

package smu.gaoyi.netty;

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

/**
 * Handles a server-side channel.
 * @author yi.gao
 *
 */
public class ServerHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	
		ByteBuf buf = (ByteBuf)msg;
		byte[] bytes = new byte[buf.readableBytes()];
		buf.readBytes(bytes);
		String message = new String(bytes, "UTF-8");
		System.out.println("服务端收到的消息: " + message);
		
		//向客户端写数据
		String response = "hello client";
		ByteBuf buffer = Unpooled.copiedBuffer(response.getBytes());
		ctx.write(buffer);//写入缓冲数组
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {	
		System.out.println("channelReadComplete...");
		ctx.flush();//将缓冲区数据写入SocketChannel
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		
		System.out.println("exceptionCaught...");
	}

	



}

客户端:

package smu.gaoyi.netty;

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 void connect(String host, int port) throws Exception {
		EventLoopGroup group = new NioEventLoopGroup();
		
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group)
					.channel(NioSocketChannel.class)
					.handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new ClientHandler());
						}
					});
					
			ChannelFuture future = bootstrap.connect(host, port).sync();
			future.channel().closeFuture().sync();
			
											
		} finally {
			group.shutdownGracefully();
		}
		
	}
	
	

	public static void main(String[] args) throws Exception {
		new Client().connect("localhost", 8888);
	}

}

客户端的handler:

package smu.gaoyi.netty;

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

public class ClientHandler extends ChannelInboundHandlerAdapter{

	private final ByteBuf byteBuf;
	
	public ClientHandler() {
		byte[] bytes = "i love you".getBytes();
		byteBuf = Unpooled.buffer(bytes.length);
		byteBuf.writeBytes(bytes);//写入buffer 
	}
	
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//向服务端发送数据
		ctx.writeAndFlush(byteBuf);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		//读取服务端发过来的数据
		ByteBuf buf = (ByteBuf)msg;
		byte[] bytes = new byte[buf.readableBytes()];
		buf.readBytes(bytes);
		String message = new String(bytes, "UTF-8");
		System.out.println("客户端收到的消息: " + message);
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值