netty 简单demo(一)

服务端

  

package com.road.nettysocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ServerHandler extends SimpleChannelInboundHandler<String>{

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg)
			throws Exception {
		System.out.println(msg);
		ctx.writeAndFlush("server").sync();  
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("连接断开 : " + ctx.channel().remoteAddress());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println("连接异常 : " + ctx.channel().remoteAddress() + " error : " + cause);
		ctx.close();
	}

}

package com.road.nettysocket;

import io.netty.bootstrap.ServerBootstrap;
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.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class NettyServer {

    private static final EventLoopGroup bossGroup = new NioEventLoopGroup(4);  
    private static final EventLoopGroup workerGroup = new NioEventLoopGroup(4); 
    
	public void bind(int port)
	{
	   ServerBootstrap b = new ServerBootstrap();
	   b.group(bossGroup,workerGroup)
	    .channel(NioServerSocketChannel.class)
	    .childHandler(new ChildChannelHandler());
	   
	   try {
		   ChannelFuture f = b.bind("127.0.0.1",port).sync();
		   f.channel().closeFuture().sync();
	   } catch (InterruptedException e) {
		    e.printStackTrace();
	   }finally
	   {
		   bossGroup.shutdownGracefully();
		   workerGroup.shutdownGracefully();
	   }
	}
	
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel>
	{
		@Override
		protected void initChannel(SocketChannel channel) throws Exception {
			channel.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));  
			channel.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));  
			channel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));  
			channel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); 
			channel.pipeline().addLast(new ServerHandler());
		
		}
	}
	
	public static void main(String[] args)
	{
		new NettyServer().bind(9500);
	}
}
客户端


package com.road.nettysocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientHandler extends SimpleChannelInboundHandler<String>{

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg)
			throws Exception {
		
		System.out.println(msg);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("连接断开 : " + ctx.channel().remoteAddress());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		System.out.println("连接异常 : " + ctx.channel().remoteAddress() + " error : " + cause);
	}
  
}
package com.road.nettysocket;

import com.road.nettydemo.TcpClient;
import com.road.nettydemo.TcpClientHandler;

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.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

public class NettyClient {

	public static Channel channel;
	 
	public void connect(int port,String host)
	{
		EventLoopGroup group = new NioEventLoopGroup();
		Bootstrap b = new Bootstrap();
		b.group(group)
		 .channel(NioSocketChannel.class)
		 .option(ChannelOption.TCP_NODELAY, true)
		 .handler(new ChildChannelHandler());
		
		b.option(ChannelOption.SO_KEEPALIVE, true);  
		
		try {
			ChannelFuture future =b.connect(host, port).sync();
			channel = future.channel();
			//channel.closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally
		{
			//group.shutdownGracefully();
		}
	}
	
	private class ChildChannelHandler extends ChannelInitializer<SocketChannel>
	{
		@Override
		protected void initChannel(SocketChannel channel) throws Exception {
			channel.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));  
			channel.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));  
			channel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));  
			channel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); 
			channel.pipeline().addLast(new ClientHandler());
		}
	}
	
	 public static void sendMsg(String msg) throws Exception {  
	        if(channel!=null){  
	            channel.writeAndFlush(msg).sync();  
	        }else{  
	            System.out.println("消息发送失败,连接尚未建立!");  
	        }  
	    }
	
	public static void main(String[] args)
	{
		new NettyClient().connect(9500, "127.0.0.1");
		
	    long t0 = System.nanoTime();  
        for (int i = 0; i < 100000; i++) {  
        	try {
				NettyClient.sendMsg(i+"你好1");
			} catch (Exception e) {
				e.printStackTrace();
			}  
        }  
	}
}



猜你喜欢

转载自blog.csdn.net/shizhan1881/article/details/71510356