netty入门demo

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

在公司最近用到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);
	}

}



展开阅读全文

没有更多推荐了,返回首页