Netty5入門(2),netty5入門

來源:互聯網
上載者:User

Netty5入門(2),netty5入門

四、Time協議

繼續測試《netty5使用者指南》中的Time協議。

1、一個封裝時間的特殊的POJO類

首先實現UnixTime類:

package com.ydtf;

 

import java.util.Date;

 

public class UnixTime {

 

    private final int value;

 

    public UnixTime() {

       this((int) (System.currentTimeMillis() / 1000L+ 2208988800L));

    }

 

    public UnixTime(int value) {

       this.value = value;

    }

 

    public int value() {

       return value;

    }

 

    @Override

    public String toString() {

       return new Date((value() - 2208988800L) *1000L).toString();

    }

}

2、將ByteBuf轉換為POJO

然後是TimeDecoder類:

package com.ydtf;

 

import java.util.List;

 

import io.netty.buffer.ByteBuf;

import io.netty.channel.ChannelHandlerContext;

import io.netty.handler.codec.ByteToMessageDecoder;

 

 

public class TimeDecoder extends ByteToMessageDecoder { // (1)

 

   @Override

   protected void decode(ChannelHandlerContext ctx, ByteBuf in,

         List<Object>out) throws Exception {

      if (in.readableBytes()< 4) {

           return;

       }

 

       out.add(new UnixTime(in.readInt()));

   }

}

3、將POJO轉換為ByteBuf

TimeEncoder,用於進行UnixTime –>ByteBuf的轉換。

package com.ydtf;

 

import io.netty.buffer.ByteBuf;

import io.netty.channel.ChannelHandlerContext;

import io.netty.handler.codec.MessageToByteEncoder;

 

public class TimeEncoder extends MessageToByteEncoder<UnixTime> {

 

   @Override

   protected void encode(ChannelHandlerContext ctx, UnixTime msg, ByteBuf out)

         throws Exception {

      out.writeInt(msg.value());

   }

}

4、服務端的處理

然後是服務端的handler:

package com.ydtf;

 

import io.netty.buffer.ByteBuf;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelFutureListener;

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

 

public classTimeServerHandler extendsChannelHandlerAdapter {

 

    @Override

    public voidchannelActive(ChannelHandlerContext ctx) {

       ChannelFuture f = ctx.writeAndFlush(new UnixTime());

       f.addListener(ChannelFutureListener.CLOSE);

    }

 

    @Override

    public voidexceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

       cause.printStackTrace();

       ctx.close();

    }

}

5、用戶端的處理

用戶端的handler:

package com.ydtf;

 

import io.netty.channel.ChannelHandlerAdapter;

import io.netty.channel.ChannelHandlerContext;

 

public classTimeClientHandler extendsChannelHandlerAdapter {

   @Override

   public voidchannelRead(ChannelHandlerContext ctx, Object msg) {

       UnixTime m = (UnixTime) msg;

       System.out.println(m);

       ctx.close();

   }

    @Override

    public voidexceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

       cause.printStackTrace();

       ctx.close();

    }

}

6、服務端主類

package com.ydtf;

 

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;

importio.netty.channel.socket.nio.NioServerSocketChannel;

 

public class TimeServer {

   private int port;

 

    public TimeServer(int port) {

       this.port = port;

    }

 

    public void run() throws Exception {

       EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)

       EventLoopGroup workerGroup = new NioEventLoopGroup();

       try {

           ServerBootstrap b = new ServerBootstrap(); // (2)

           b.group(bossGroup, workerGroup)

            .channel(NioServerSocketChannel.class) // (3)

            .childHandler(newChannelInitializer<SocketChannel>() { // (4)

                 @Override

                 public voidinitChannel(SocketChannel ch) throws Exception {

                     ch.pipeline().addLast(new TimeEncoder(), new TimeServerHandler());

                 }

            })

            .option(ChannelOption.SO_BACKLOG, 128)          // (5)

            .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

 

           ChannelFuture f = b.bind(port).sync(); // (7)

           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 TimeServer(port).run();

    }

}

7、用戶端主類

packagecom.ydtf;

 

importio.netty.bootstrap.Bootstrap;

importio.netty.channel.ChannelFuture;

importio.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

importio.netty.channel.EventLoopGroup;

importio.netty.channel.nio.NioEventLoopGroup;

importio.netty.channel.socket.SocketChannel;

importio.netty.channel.socket.nio.NioSocketChannel;

 

publicclass TimeClient {

    public static void main(String[] args)throws Exception {

        String host = args[0];

        int port = Integer.parseInt(args[1]);

        EventLoopGroup workerGroup = newNioEventLoopGroup();

 

        try {

            Bootstrap b = new Bootstrap(); //(1)

           b.group(workerGroup); // (2)

            b.channel(NioSocketChannel.class);// (3)

           b.option(ChannelOption.SO_KEEPALIVE, true); // (4)

            b.handler(newChannelInitializer<SocketChannel>() {

                @Override

                public voidinitChannel(SocketChannel ch) throws Exception {

                    ch.pipeline().addLast(newTimeDecoder(), new TimeClientHandler());

                }

            });

 

            // Start the client.

            ChannelFuture f = b.connect(host,port).sync(); // (5)

 

            // Wait until the connection isclosed.

            f.channel().closeFuture().sync();

        } finally {

            workerGroup.shutdownGracefully();

        }

    }

}

8、運行

在TimeServer.java上右鍵,Run as >> Java Application,啟動服務端。

然後在TimeClient.java上右鍵,Run as >> Run Configurations…,在彈出的視窗中設定Name和Main Class:

Name設定一個和現有配置不重複的就可以了,比如TimeClient1、TimeClien(2)等。點擊Mainclass右邊的Search…按鈕,選擇TimeClient類。

然後點Arguments,添加兩個運行參數localhost和8080:


然後點擊視窗右下角的Run按鈕。這是你將在用戶端的Console視窗中看見一個日期輸出。

如果想分別查看服務端和用戶端的Console輸出,請點擊Display Selected Console按鈕:



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.