NIO系列-03-NIO

声明

该系列文章由书籍《Netty权威指南》第二版整理而来。只为记录学习笔记。
若认为内容侵权请及时通知本人删除相关内容。

时间服务器–NIO

服务端代码

服务端主程序

public class TimeServer {
    public static void main(String[] args) {
        int port = 1234;

        try {
            TimeServerDispatcher timeServer;
            timeServer = new TimeServerDispatcher(port);
            new Thread(timeServer).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

服务端处理类

public class TimeServerDispatcher implements Runnable {

    private Selector selector;

    private ServerSocketChannel ssc;

    private volatile boolean stop;

    private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public TimeServerDispatcher(int port) throws IOException {
        selector = Selector.open();
        ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.socket().bind(new InetSocketAddress(port), 10000);
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("The time server is listening on port : " + port);
    }

    public void stop() {
        this.stop = true;
    }

    @Override
    public void run() {
        while (!this.stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                for (SelectionKey k : selectedKeys) {
                    selectedKeys.remove(k);
                    try {
                        doProcessRequest(k);
                    } catch (Exception e) {
                        if (k != null) {
                            k.cancel();
                            if (k.channel() != null)
                                k.channel().close();
                        }
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void doProcessRequest(SelectionKey key) throws IOException {

        if (!key.isValid())
            return;

        if (key.isAcceptable()) {
            ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
            SocketChannel sc = ssc.accept();
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ);
        }
        if (key.isReadable()) {
            SocketChannel sc = (SocketChannel) key.channel();
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int len = sc.read(readBuffer);
            if (len > 0) {
                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                String reqMsg = new String(bytes, "UTF-8");
                System.out.println("request msg is : " + reqMsg);
                String respMsg = this.df.format(new Date());
                doResponse(sc, respMsg);
            } else if (len < 0) {
                key.cancel();
                sc.close();
            } else {
                // 0
            }
        }
    }

    private void doResponse(SocketChannel sc, String respMsg) throws IOException {
        if (respMsg == null)
            return;

        byte[] bytes = respMsg.getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        sc.write(writeBuffer);
    }
}

客户端代码

客户端主程序

public class TimeClient {

    public static void main(String[] args) {

        int port = 1234;
        new Thread(new TimeClientHandler("127.0.0.1", port)).start();
    }
}

客户端处理程序

public class TimeClientHandler implements Runnable {

    private String host;
    private int port;

    private Selector selector;
    private SocketChannel socketChannel;

    private volatile boolean stop;

    public TimeClientHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            if (socketChannel.connect(new InetSocketAddress(host, port))) {
                socketChannel.register(selector, SelectionKey.OP_READ);

                doSendReqMsg(socketChannel, "Hi Server !");
            } else
                socketChannel.register(selector, SelectionKey.OP_CONNECT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        while (!this.stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> selectedKeys = selector.selectedKeys();
                for (SelectionKey k : selectedKeys) {
                    selectedKeys.remove(k);
                    try {
                        doProcessResponse(k);
                    } catch (Exception e) {
                        if (k != null) {
                            k.cancel();
                            if (k.channel() != null)
                                k.channel().close();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void doProcessResponse(SelectionKey key) throws IOException {

        if (!key.isValid())
            return;

        SocketChannel sc = (SocketChannel) key.channel();

        if (key.isConnectable()) {
            if (sc.finishConnect()) {
                sc.register(selector, SelectionKey.OP_READ);
                doSendReqMsg(sc, "Hi Server !");
            } else {
                throw new RuntimeException("连接失败");
            }
        }
        if (key.isReadable()) {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                String respMsg = new String(bytes, "UTF-8");
                System.out.println("time : " + respMsg);
                this.stop = true;
            } else if (readBytes < 0) {
                key.cancel();
                sc.close();
            } else {
                // 0
            }
        }
    }

    private void doSendReqMsg(SocketChannel sc, String reqMsg) throws IOException {
        byte[] req = reqMsg.getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        sc.write(writeBuffer);
    }

}

总结

这种模型有如下特点:

  • 客户端的连接操作时异步的
  • SocketChannel的读写操作是异步的
  • 一个Selector可以处理成千上万个客户端连接

但是:

  • 代码复杂
  • 这里的实现可能出现 “读半包”,”写半包”的情况

参考资料: 《Netty权威指南》第二版

内容概要:本文围绕基于模型预测控制(MPC)与滚动时域估计(MHE)集成的目标点镇定展开研究,重点探讨了在动态系统中如何通过MPC实现精确控制,同时利用MHE进行状态估计以提升系统鲁棒性和精度。文中结合Matlab代码实现,展示了MPC与MHE协同工作的算法流程、数学建模过程及仿真验证,尤其适用于存在噪声或部分可观测的复杂系统环境。该方法能够有效处理约束条件下的最优控制问题,并实时修正状态估计偏差,从而实现对目标点的稳定镇定。; 适合人群:具备一定自动控制理论基础和Matlab编程能力的高校研究生、基于模型预测控制(MPC)与滚动时域估计(MHE)集成的目标点镇定研究(Matlab代码实现)科研人员及从事控制系统开发的工程技术人员;熟悉状态估计与最优控制相关概念的研究者更为适宜; 使用场景及目标:①应用于机器人控制、航空航天、智能制造等需要高精度状态估计与反馈控制的领域;②用于深入理解MPC与MHE的耦合机制及其在实际系统中的实现方式,提升对预测控制与状态估计算法的综合设计能力; 阅读建议:建议读者结合提供的Matlab代码进行仿真实践,重点关注MPC代价函数构建、约束处理、滚动优化过程以及MHE的滑动窗口估计机制,同时参考文中可能涉及的卡尔曼滤波、最小均方误差等辅助方法,系统掌握集成架构的设计思路与调参技巧。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值