netty基础--基本收发

    使用maven构建一个基本的netty收发应用,作为其他应用的基础。客户端使用packet sender工具。

1  添加netty依赖

1  maven netty依赖

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.0.0.Final</version>
</dependency>

2  添加ServerBootstrap启动函数

package io.netty.example.basic;
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;

/**
* main class
* @author Sylar
* @Time 2017-01-02
*/
public class NettyBaisc {

    private int port;
    public NettyBaisc(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
           
            /*创建一个新的 ServerBootstrap 来创建和绑定新的 Channel
            指定 EventLoopGroups 从 ServerChannel 和接收到的管道来注册并获取 EventLoops
            指定 Channel 类来使用
            设置处理器用于处理接收到的管道的 I/O 和数据
            通过配置的引导来绑定管道
            ChannelInitializer 负责设置 ChannelPipeline
            实现 initChannel() 来添加需要的处理器到 ChannelPipeline。一旦完成了这方法 ChannelInitializer 将会从 ChannelPipeline 删除自身。*/
           
            ServerBootstrap b = new ServerBootstrap(); // (2)
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)
             .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.pipeline().addLast(new NettyBaiscHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)

            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 8080;
        }
        new NettyBaisc(port).run();
    }
}

3  添加通道handler

package io.netty.example.basic;

import java.io.UnsupportedEncodingException;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
/**
* handler class
* @author Sylar
* @Time 2017-01-02
*/
public class NettyBaiscHandler extends ChannelInboundHandlerAdapter { // (1)
     @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(">>>>>>>>connect in>>>>>>>>");
        }
     @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.out.println(">>>>>>>>connect out>>>>>>>>");
        }
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
       
        /*byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req);       
        System.out.println("Server received: " + body);*/
       
        System.out.println("Client received: " + buf.toString(CharsetUtil.UTF_8));
        ctx.writeAndFlush(Unpooled.copiedBuffer("Ack", CharsetUtil.UTF_8));
        /*ctx.write(Unpooled.copiedBuffer("Ack", CharsetUtil.UTF_8));
        ctx.flush();*/
    }
   /* public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        // Discard the received data silently.
        //((ByteBuf) msg).release(); // (3)
        ByteBuf in = (ByteBuf) msg;
        try {
            while (in.isReadable()) { // (1)
                System.out.print((char) in.readByte());
                System.out.flush();
            }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }
    }*/

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

4  参考

  • netty官网的echo示例

             http://netty.io/wiki/user-guide-for-4.x.html

  • channel不能发送string的问题说明

             (我在去年底的测试中是可以直接发送字符串的,有些奇怪!)

             http://stackoverflow.com/questions/25760764/netty-channel-write-not-writing-message

posted on 2017-04-19 18:22  猫不白  阅读(903)  评论(0编辑  收藏  举报

导航