039_Netty网络编程服务端入门程序开发

java 复制代码
package com.ruyuan.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;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {

    private int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        // 肯定需要线程池,有的线程可以去负责跟大量的客户端建立网络连接
        // 有的线程可以去负责网络io数据读写
        // 网络io数据读取出来以后,处理请求数据,数据处理也需要专门的线程去处理
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // 默认的线程池的大小,cpu core * 2
        EventLoopGroup workerGroup = new NioEventLoopGroup(20);

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new StringDecoder())
                                    .addLast(new StringEncoder())
                                    .addLast(new NettyServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println("starting netty server......");
        int port = 8998;
        if(args.length > 0) {
            port = Integer.parseInt(args[0]);
        }
        new NettyServer(port).start();
    }

}
java 复制代码
package com.ruyuan.netty;

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

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    // 网络连接tcp三次握手后,建立和封装一个channel,网络连接的通信管道
    // 此时这个channel应该就是可以实现一个激活
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel active......");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channel read: " + (String)msg);

        String response = "hello world......";
        ByteBuf responseByteBuf = Unpooled.buffer();
        responseByteBuf.writeBytes(response.getBytes());

        ctx.channel().writeAndFlush(responseByteBuf);
        System.out.println("channel write: " + response);
    }

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

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();;
        ctx.close();
    }
}
相关推荐
薛定谔的悦5 小时前
MQTT通信协议业务层实现的完整开发流程
java·后端·mqtt·struts
enjoy嚣士6 小时前
springboot之Exel工具类
java·spring boot·后端·easyexcel·excel工具类
无限大66 小时前
职场逻辑03:3步搞定高效汇报,让领导看到你的价值
后端
盐水冰7 小时前
【烘焙坊项目】后端搭建(12) - 订单状态定时处理,来单提醒和顾客催单
java·后端·学习
紫丁香7 小时前
AutoGen详解一
后端·python·flask
小涛不学习7 小时前
Spring Boot 详解(从入门到原理)
java·spring boot·后端
Victor3569 小时前
MongoDB(51)什么是分片?
后端
Victor3569 小时前
MongoDB(50)副本集中的角色有哪些?
后端
IT_陈寒10 小时前
JavaScript开发者必看:5个让你的代码性能翻倍的隐藏技巧
前端·人工智能·后端
shengjk110 小时前
大数据工程师必看:为什么你的 IN 查询在 Flink/Spark 上慢到离谱?
后端