1. 程式人生 > >Netty入門示例(一)

Netty入門示例(一)

以下演示的是一個時間伺服器。

依次啟動Server,Client;Client從伺服器上讀取得時間後列印的控制檯上。

ChannelInitializer,ChannelInboundHandlerAdapter

Server

提供時間服務。
監聽8080埠,子類TimeServerHandlerAdapterChannelInboundHandlerAdapter的一個實現。
通過實現方法channelActive,在新請求進入時輸入本機的時間。
通過實現方法exceptionCaught捕獲異常。

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; public class Server { public static void main(String[] args) { new Server().
bind(8080); } private void bind(int port) { EventLoopGroup boosGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(boosGroup, workerGroup); bootstrap.channel(
NioServerSocketChannel.class); bootstrap.option(ChannelOption.SO_BACKLOG, 2014); // init bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { // bind socketChannel.pipeline().addLast(new TimeServerHandlerAdapter()); } }); try { ChannelFuture future = bootstrap.bind(port).sync(); future.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); } finally { boosGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } // adapter class TimeServerHandlerAdapter extends ChannelInboundHandlerAdapter { @Override public void channelActive(final ChannelHandlerContext ctx) { final ByteBuf time = ctx.alloc().buffer(4); time.writeLong(System.currentTimeMillis()); // write data final ChannelFuture f = ctx.writeAndFlush(time); f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { assert f == future; ctx.close(); } }); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } }

Client

呼叫伺服器時間,列印在控制檯上。

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Date;

public class Client {

   public static void main(String[] args) throws Exception {
       new Client().connect("127.0.0.1", 8080);
   }

   private void connect(String host, int port) throws InterruptedException {
       EventLoopGroup workerGroup = new NioEventLoopGroup();
       Bootstrap bs = new Bootstrap();
       bs.group(workerGroup);
       bs.channel(NioSocketChannel.class);
       bs.option(ChannelOption.SO_KEEPALIVE, true);

       // init
       bs.handler(new ChannelInitializer<SocketChannel>() {
           @Override
           public void initChannel(SocketChannel ch) throws Exception {
               ch.pipeline().addLast(new TimeClientHandlerAdapter());
           }
       });
       try {
           ChannelFuture f = bs.connect(host, port).sync();
           f.channel().closeFuture().sync();
       } finally {
           workerGroup.shutdownGracefully();
       }
   }

   // adapter
   class TimeClientHandlerAdapter extends ChannelInboundHandlerAdapter {
       @Override
       public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
           ByteBuf buf = (ByteBuf) msg;
           try {

               // read data
               System.out.println(new Date(buf.readLong()));
               ctx.close();
           } finally {
               buf.release();
           }
       }

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