netty學習一

創建EchoServer

package com.gg.Mynetty;

import com.gg.Mynetty.handler.EchoServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
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.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class EchoServer {
	private final int port;
	public EchoServer(int port) {
		this.port = port;
	}
	public void start() {
		EventLoopGroup group = new NioEventLoopGroup();
		ServerBootstrap server = new ServerBootstrap();
		server.group(group)
		.childOption(ChannelOption.SO_KEEPALIVE, true)
		.channel(NioServerSocketChannel.class)
		.childHandler(new ChannelInitializer<Channel>() {

			@Override
			protected void initChannel(Channel ch) throws Exception {
//				ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
//				ch.pipeline().addLast(new StringDecoder());
				ch.pipeline().addLast(new EchoServerHandler());
				
			}
			
		});
		
		ChannelFuture f;
		try {
			f = server.bind(port).sync();
			System.out.println(EchoServer.class.getName() + " started and listern on " + f.channel().localAddress());
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			group.shutdownGracefully();
			
		}
		
	}
	
	public static void main(String[] args) {
		new EchoServer(8090).start();
	}
}

創建ServerHandler

package com.gg.Mynetty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

public class EchoServerHandler extends ChannelInboundHandlerAdapter{
	
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("server 連接已經建立");
		super.channelActive(ctx);
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("收到請求數據begin>>>>>>>>>>>>>>>");
		ByteBuf buf = (ByteBuf)msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req,"UTF-8");
		System.out.println("收到請求數據body>>>>>>>>>>>>>>>"+body);
		//這行代碼無法發送數據,緩衝區數據無法被連續使用
		//ChannelFuture f =  ctx.writeAndFlush(msg);
		System.out.println("收到請求數據end>>>>>>>>>>>>>>>");
		ChannelFuture f =  ctx.writeAndFlush(Unpooled.copiedBuffer(body.getBytes()));
		//此代碼服務端主動用來關閉客戶端鏈接
		//f.addListener(ChannelFutureListener.CLOSE);
		
	}
	
	
	
}

創建Client

package com.gg.Mynetty;

import java.net.InetSocketAddress;

import com.gg.Mynetty.handler.EchoClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
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.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class EchoClient {
	private final String host;
	private final int port;
	
	public EchoClient(String host,int port) {
		this.port = port;
		this.host = host;
	}
	
	public void start() throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();
		Bootstrap b = new Bootstrap();
		b.group(group).channel(NioSocketChannel.class)
		.option(ChannelOption.SO_KEEPALIVE, true)
		.handler(new ChannelInitializer<Channel>() {
			@Override
			protected void initChannel(Channel ch) throws Exception {
//				ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
//				ch.pipeline().addLast(new StringDecoder());
				ch.pipeline().addLast(new EchoClientHandler());
			}
		});
		
		
		try {
			ChannelFuture f = b.connect(host,port).sync();
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			group.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) {
		try {
			new EchoClient("127.0.0.1", 8090).start();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

創建ClientHandler

package com.gg.Mynetty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
	
	
	/**
	 * 激活時向server發送消息
	 */
	@Override
	public void channelActive(final ChannelHandlerContext ctx) throws Exception {
		System.out.println("client 連接已經建立");
		String str = "你好,netty Server";
//		for(int i = 0; i < 10; i ++) {
			ByteBuf buffer = ctx.alloc().buffer(str.length());
			buffer.writeBytes(str.getBytes());
			ctx.writeAndFlush(buffer);
//		}
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		byte[] bytes = new byte[msg.readableBytes()];
		msg.readBytes(bytes);
		String body = new String(bytes,"UTF-8");
		System.out.println("Client received "+ body);
		//客戶端主動斷開與服務端的鏈接
		//ctx.close();
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("client inactive");
		super.channelInactive(ctx);
	}
	
	
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    	System.out.println("client handlerRemoved");
    	super.handlerRemoved(ctx);
    }
}

測試結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章