zoukankan      html  css  js  c++  java
  • Apache MINA 基于UDP实例

    1、基于UDP服务端

    server

    NioDatagramAcceptor acceptor = new NioDatagramAcceptor();
    acceptor.setHandler(new MemoryMonitorHandler(this));
    DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
    chain.addLast("logger", new LoggingFilter());
    DatagramSessionConfig dcfg = acceptor.getSessionConfig();
    dcfg.setReuseAddress(true);acceptor.bind(new InetSocketAddress(PORT));
    @Override
    public void sessionCreated(IoSession session) throws Exception {
        SocketAddress remoteAddress = session.getRemoteAddress();
        server.addClient(remoteAddress);
    }
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        if (message instanceof IoBuffer) {
            IoBuffer buffer = (IoBuffer) message;
            SocketAddress remoteAddress = session.getRemoteAddress();
            server.recvUpdate(remoteAddress, buffer.getLong());
        }
     }
    @Override
    public void sessionClosed(IoSession session) throws Exception {
        System.out.println("Session closed...");
        SocketAddress remoteAddress = session.getRemoteAddress();
        server.removeClient(remoteAddress);
    }

    client:

    connector = new NioDatagramConnector();
    connector.setHandler( this );
    ConnectFuture connFuture = connector.connect( new InetSocketAddress("localhost", MemoryMonitor.PORT ));
    connFuture.addListener( new IoFutureListener(){
                public void operationComplete(IoFuture future) {
                    ConnectFuture connFuture = (ConnectFuture)future;
                    if( connFuture.isConnected() ){
                        session = future.getSession();
                        try {
                            sendData();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        log.error("Not connected...exiting");
                    }
                }
            });
    private void sendData() throws InterruptedException {
        for (int i = 0; i < 30; i++) {
            long free = Runtime.getRuntime().freeMemory();
            IoBuffer buffer = IoBuffer.allocate(8);
            buffer.putLong(free);
            buffer.flip();
            session.write(buffer);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new InterruptedException(e.getMessage());
            }
        }
    }
  • 相关阅读:
    Bash Shell 快捷键
    vector-swap
    vector-swap
    vector-size
    Android网络篇
    应用 Valgrind 发现 Linux 程序的内存问题
    树莓派初学者?先做做这十个项目吧
    树莓派 (为学习计算机编程教育设计的一种微型电脑)
    微软windows10 IOT支持PI3之后,树莓派3更是将获得Android官方原生支持
    Linux基金会宣布JS Foundation基金会成立 前身为jQuery团队
  • 原文地址:https://www.cnblogs.com/quyongjin/p/3128277.html
Copyright © 2011-2022 走看看