Netty開發的例子

一個Echo開發的例子的服務器端口

public class EchoServer {
    //具體的連接方法如下
    public void bind(int port) throws Throwable{
        //創建一個線程組
        NioEventLoopGroup parent=new NioEventLoopGroup();
        NioEventLoopGroup work=new NioEventLoopGroup();
        try {
            //創建一個服務器輔助啓動類
            ServerBootstrap server=new ServerBootstrap();
            //設置一個這服務器的二個線程組
            server.group(parent, work);
            //給這個服務器設置一個配置的參數
            server.option(ChannelOption.SO_BACKLOG,1024)
                  .option(ChannelOption.SO_KEEPALIVE,true)
                  .channel(NioServerSocketChannel.class)
                  .handler(new LoggingHandler())//這個是日誌的處理類
                  .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //進行做一些編碼和解碼的操作
                        ByteBuf delimiter=Unpooled.copiedBuffer("$_".getBytes());
                        //現在進行創建一個以特定的字符串分割解碼器
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,delimiter));
                        //進行創建一個字符串的編碼器
                        ch.pipeline().addLast(new StringDecoder());
                        //註冊一個接收數據的通道處理器對象
                        ch.pipeline().addLast(new ServerHandler());
                        //先進行解碼操作
                        ch.pipeline().addLast(new StringEncoder());
                        }
                });
            //進行阻塞的處理
            ChannelFuture future=server.bind(port).sync();
            myMetaData(future.channel());
            System.out.println();
            //進行阻塞處理
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            parent.shutdownGracefully();
            work.shutdownGracefully();
        }


    }

    private void myMetaData(Channel channel) {
        // TODO Auto-generated method stub
        System.out.println(channel.isRegistered());//判斷一下我們有數據是否是能夠
        System.out.println(channel.id());//生成的唯一的id
        System.out.println(channel.parent());//當前Channel的父類的RDD

    }

    public static void main(String[] args) {
        //定義端口
        int port=8888;
        try {
            new EchoServer().bind(port);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

對應的處理事件爲

public class ServerHandler extends ChannelInboundHandlerAdapter {
    private int count=0;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//      System.out.println("有數據來了...");
        //進行數據的註冊處理如下
        if(msg instanceof String){
            String data=(String)msg;
            System.out.println("this is "+ ++count +" timer recevive client : ["+data+"]");
            data+="$_";
            //進行編碼處理
            ByteBuf echo=Unpooled.copiedBuffer(data.getBytes());
            //發送數據回去給客戶端
            ctx.pipeline().writeAndFlush(echo);
//          ctx.pipeline().writeAndFlush(data);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }

}

客戶端的代碼如下

public class EchoClient {
    //進行數據的連接方法
    public void connect(String host,int port){
        NioEventLoopGroup event=new NioEventLoopGroup();
        try{
            //創建一個客戶端輔助啓動類
            Bootstrap client=new Bootstrap();
            //進行數據的基本的綁定
            client.group(event)
                  .option(ChannelOption.SO_SNDBUF,1024)
                  .option(ChannelOption.SO_TIMEOUT,3000)
                  .channel(NioSocketChannel.class)
                  .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //進行基本的數據解碼
                        ByteBuf buf=Unpooled.copiedBuffer("$_".getBytes());
                        //進行數據的基本的註冊
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(Integer.MAX_VALUE,buf));
                        //數據的解碼
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new ClientHandler());

                    }
                });
            //發送sync連接操作
            ChannelFuture future=client.connect(host, port).sync();

            //進行基本的等待
            future.channel().closeFuture().sync();

        }catch(Exception e){

        }finally{
            event.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        String host="localhost";
        int port=8888;
        new EchoClient().connect(host, port);
    }
}

對應的處理事件爲

public class ClientHandler extends ChannelInboundHandlerAdapter {
    private int count=0;
    //準備數據
    private final String ECHO_REQ="Hi yanghailong. welcome to Netty.$_";
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        for(int i=0;i<10;i++){
            //一開啓啓動調用這個方法,然後就開始寫數據到我們的服務器
            ctx.writeAndFlush(Unpooled.copiedBuffer(ECHO_REQ.getBytes()));
        }
    }

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

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("this is "+ ++count +" timer recevive client : ["+msg+"]");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }

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