NIO学习计划之netty服务端与客户端的编写

需要的依赖:

        
            io.netty
            netty-all
            5.0.0.Alpha2
        

服务端handler:

package cn.lix.nio.demo.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);
        String body = new String(req, "utf-8");
        System.out.println("Server :" + body);
        String response = "进行返回给客户端的响应:" + body;
        channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
    }
}

server:

package cn.lix.nio.demo.netty;

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 NettyServer {

    public static void main(String[] args) {
        //服务类
        ServerBootstrap bootStrap = new ServerBootstrap();
        //主要负责监听任务与分发
        EventLoopGroup boss = new NioEventLoopGroup(2);
        //主要负责任务的具体执行
        EventLoopGroup worker = new NioEventLoopGroup(10);

        bootStrap.group(boss, worker);

        bootStrap.channel(NioServerSocketChannel.class)// 指定NIO的模式
                .option(ChannelOption.SO_BACKLOG, 1024)// 设置tcp缓冲区
                .option(ChannelOption.SO_SNDBUF, 32 * 1024)// 设置发送缓冲大小
                .option(ChannelOption.SO_RCVBUF, 32 * 1024)// 这是接收缓冲大小
                .option(ChannelOption.SO_KEEPALIVE, true)// 保持连接
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new NettyServerHandler());
                    }
                });
        try {
            // 4 进行绑定
            ChannelFuture channelFuture = bootStrap.bind(8888).sync();
            // 5 等待关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }


}

客户端handler:

package cn.lix.nio.demo.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        byte[] req = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(req);

        String body = new String(req, "utf-8");
        System.out.println("Client :" + body);
    }
}


client:

package cn.lix.nio.demo.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {

    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup(2);
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel sc) throws Exception {
                sc.pipeline().addLast(new NettyClientHandler());
            }
        });

        try {
            ChannelFuture channelFuture = b.connect("127.0.0.1", 8888).syncUninterruptibly();
            // 发送消息
            channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("发送第1条测试消息".getBytes()));
            // 等待关闭
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }
}

-----------------------------------以下为测试http server--------------------------------------

HTTP Handler:

package cn.lix.nio.demo.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;


public class HttpHandler extends SimpleChannelInboundHandler<FullHttpRequest> {


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelReadComplete");
        super.channelReadComplete(ctx);
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        if(null != cause) cause.printStackTrace();
        if(null != ctx) ctx.close();
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
        String ss = fullHttpRequest.content().toString(CharsetUtil.UTF_8);
        System.out.println("接收到参数:" + ss);// 使用post传递的参数
        System.out.println("class:" + fullHttpRequest.getClass().getName());
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer("OK".getBytes())); // 2

        HttpHeaders heads = response.headers();
        heads.add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN + "; charset=UTF-8");
        heads.add(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(response.content().readableBytes())); // 3
        heads.add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

        channelHandlerContext.write(response);
    }
}

HTTP Server:

package cn.lix.nio.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

public class HttpServer {

    private final int port = 8080;// http端口为8080

    public HttpServer() {
    }

    public static void main(String[] args) throws Exception {
        new HttpServer().start();// 启动服务
    }

    public void start() throws Exception {
        ServerBootstrap b = new ServerBootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        b.group(group)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("initChannel ch:" + ch);
                        ch.pipeline()
                                .addLast("decoder", new HttpRequestDecoder())
                                .addLast("encoder", new HttpResponseEncoder())
                                .addLast("aggregator", new HttpObjectAggregator(65536))
                                .addLast("handler", new HttpHandler());    //ParseRequestHandler
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128) // determining the number of connections queued
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);

        b.bind(port).sync();
        // 不让线程销毁
        System.in.read();
    }
}

postman请发起求:
NIO学习计划之netty服务端与客户端的编写_第1张图片
后端console结果:
NIO学习计划之netty服务端与客户端的编写_第2张图片

更多netty相关学习内容请点击:https://www.w3cschool.cn/essential_netty_in_action/essential_netty_in_action-un8q288w.html

你可能感兴趣的:(TCP,netty,nio)