快速搭建 netty服务器

前言

使用idea快速搭建基于maven的netty服务器项目

1.新建空白maven项目

file-new-project

选择maven空白项目,输入groupid和artifactid,一路点next
快速搭建 netty服务器_第1张图片

2.引入netty maven 依赖

pom.xml 文件加入netty-all 依赖


io.netty
netty-all
4.1.42.Final


3.服务器代码

tcp套接字server

创建ServerBootstrap,io模式为nio。同时自定义handler消息处理。

server代码:

    public static void main(String[] args) throws InterruptedException {
        //config the server
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try{
            ServerBootstrap b = new ServerBootstrap();
            b.channel(NioServerSocketChannel.class)
                    .group(bossGroup,workerGroup)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new LoggingHandler(LogLevel.INFO))
                                    .addLast(new EchoServerHandler());
                        }
                    });

            //start the server
            ChannelFuture future = b.bind(8090).sync();

            //wait until server is closed
            future.channel().closeFuture().sync();


        }finally {
            //shut down the event loop to terminate all threads
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }


    }

handler代码:

public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.write(msg);
    }


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

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

}

http server

server 代码

public class HttpHelloWorldServer {
    public static void main(String[] args) throws InterruptedException {

        //config the server
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup group = new NioEventLoopGroup();
        try{
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,group)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer(){

                        protected void initChannel(Channel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new HttpServerCodec())
                                    .addLast(new HttpServerExpectContinueHandler())
                                    .addLast(new HttpHelloWorldServerHandler());
                        }
                    });

            //start the server
            ChannelFuture future = b.bind(8090).sync();

            System.out.println("open you browser and navigate to 127.0.0.1:8090");

            //wait until server is closed
            future.channel().closeFuture().sync();


        }finally {
            bossGroup.shutdownGracefully();
            group.shutdownGracefully();
        }

    }
}

handler代码

public class HttpHelloWorldServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    private static final byte[] CONTENT = "helloworld".getBytes();

    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpRequest){
            HttpRequest request = (HttpRequest) msg;
            FullHttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), OK,Unpooled.wrappedBuffer(CONTENT));
            response.headers()
                    .set(CONTENT_TYPE, TEXT_PLAIN)
                    .setInt(CONTENT_LENGTH, response.content().readableBytes());

            ChannelFuture f = ctx.write(response);
        }

    }

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

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

测试

首先测试tcp server。我们同时新建一个客户端与server进行交互:
client代码

public class EchoClient {

    public static void main(String[] args) throws InterruptedException {
        //config the client
        EventLoopGroup group = new NioEventLoopGroup();
        try{

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new LoggingHandler(LogLevel.INFO))
                                    .addLast(new EchoClientHandler());

                        }
                    });

            //start the client
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8090).sync();
            //wait until the connection is closed
            future.channel().closeFuture().sync();
        }finally {
            //shut down the event loop to terminate all threads
            group.shutdownGracefully();
        }


    }
}

clienhandler

public class EchoClientHandler extends ChannelInboundHandlerAdapter {


    private final ByteBuf firstMsg;


    public EchoClientHandler() {
        this.firstMsg = Unpooled.wrappedBuffer("i am echo message".getBytes());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(firstMsg);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.write(msg);
    }


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

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

先启动server,绑定端口8090。再启动client。连接server。
server日志:
快速搭建 netty服务器_第2张图片
client 日志
快速搭建 netty服务器_第3张图片
可以看到客户端向服务器发送了一条消息,服务器收到消息原封不动回复客户端,客户端收到消息又原封不同回复服务器。像互相踢皮球一样。

然后再看下http server:
启动HttpHelloworldServer,然后打开浏览器访问http://127.0.0.1:8090。页面会出现helloworld的文字。
快速搭建 netty服务器_第4张图片

server日志
快速搭建 netty服务器_第5张图片

最后

示例代码: my-netty-example

你可能感兴趣的:(netty)