netty简单例子

一、客户端

package com.yylcslg.example.netty.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yylcslg.client.netty.echo.EchoClientHandler;

import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;

/**
 * 
 * 
 * 
 * @author 14041292
 *
 */
public class NettyClient {
	
	private final static Logger logger = LoggerFactory.getLogger(NettyClient.class);
	
    static final String HOST = "127.0.0.1";
    static final int PORT = 8008;
	
	public void connection() throws Exception{
		
		EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
             .option(ChannelOption.TCP_NODELAY, true)
             .handler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new EchoClientHandler());
                 }
             });

            // Start the client.
            ChannelFuture f = b.connect(HOST, PORT).sync();

            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down the event loop to terminate all threads.
            group.shutdownGracefully();
        }
		
	}
	
	
	public static void main(String[] args) throws Exception{
		logger.info("client start.............");
		new NettyClient().connection();
	}

}

 

二、客户端处理类

package com.yylcslg.example.netty.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yylcslg.example.netty.util.DataUtil;


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

public class NettyClientHandler extends ChannelHandlerAdapter{

	
	private final static Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);
	
    private final ByteBuf msgBuf;

    /**
     * Creates a client-side handler.
     */
    public NettyClientHandler() {
    	String str = "yin yun long";
    	
    	byte[] strByte = str.getBytes();
    	msgBuf = Unpooled.buffer(strByte.length);
    	msgBuf.writeBytes(strByte);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        ctx.writeAndFlush(msgBuf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        
        String respMsg = DataUtil.msgToStr(msg);
        logger.info("client recevie: " + respMsg);
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
       ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
	
}


三、服务端

package com.yylcslg.example.netty.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yylcslg.client.netty.echo.EchoServerHandler;

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;

/**
 * 
 * 
 * @author 14041292
 *
 */
public class NettyServer {
	
	private final static Logger logger = LoggerFactory.getLogger(NettyServer.class);
	
	static final int PORT = 8008;
	
	public void bind() throws Exception{
		EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .option(ChannelOption.SO_BACKLOG, 100)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new EchoServerHandler());
                 }
             });

            // Start the server.
            ChannelFuture f = b.bind(PORT).sync();

            // Wait until the server socket is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down all event loops to terminate all threads.
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
		
	}
	
	
	
	public static void main(String[] args) throws Exception{
		logger.info("server start..............");
		
		new NettyServer().bind();
	}

}

 

四、服务端处理类

package com.yylcslg.example.netty.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yylcslg.example.netty.util.DataUtil;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;


/**
 * netty 服务端处理
 * 
 * 
 * @author 14041292
 *
 */
public class NettyServerHandler extends ChannelHandlerAdapter {
	
	private final static Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
	    	
		String respMsg = DataUtil.msgToStr(msg);
		logger.info("server recevie: " + respMsg);
		String tempStr="pass to client !!!";
	    ctx.write(Unpooled.copiedBuffer(tempStr.getBytes()));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}

 


猜你喜欢

转载自yylcslg.iteye.com/blog/2281293