天天看點

java netty伺服器簡單例子

java netty 伺服器簡單例子

例子實作的功能是用戶端連接配接伺服器,伺服器傳回目前時間的例子,使用maven導入netty的包,其pom依賴為:

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

處理網絡資料的程式如下:

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.io.UnsupportedEncodingException;

public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    //有連接配接可以讀取
    @Override
    public void channelRead(ChannelHandlerContext ctx,Object msg){
        ByteBuf buf = (ByteBuf)msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        try {
            String body = new String(req,"UTF-8");
            System.out.println("The time server receive order :" + body);
            String currentTime = System.currentTimeMillis()+"";
            ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
            ctx.write(resp);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

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

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
        System.out.println(cause.toString());
        ctx.close();
    }
}           

伺服器初始化的程式如下:

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;

public class TimeServer {
    public void bind(int port) throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try{
        ServerBootstrap b = new ServerBootstrap();
        /*最大連接配接數量設定 BACKLOG用于構造服務端套接字ServerSocket對象,辨別當伺服器請求處理線程全滿時,用于臨時存放已完成三次握手的請求的隊列的最大長度。如果未設定或所設定的值小于1,Java将使用預設值50。*/
        b.group(bossGroup,workGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG,1024).childHandler(new ChildChannelHandler());
        //綁定端口,等待同步成功
        ChannelFuture f = b.bind(port).sync();
        f.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {

        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(new TimeServerHandler());
        }
    }

    public static void main(String[] args){
        int port = 9000;
        try {
            new TimeServer().bind(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}           

使用網絡助手進行調試,結果如下:

java netty伺服器簡單例子