Example usage for org.apache.mina.transport.nio NioTcpServer NioTcpServer

List of usage examples for org.apache.mina.transport.nio NioTcpServer NioTcpServer

Introduction

In this page you can find the example usage for org.apache.mina.transport.nio NioTcpServer NioTcpServer.

Prototype

public NioTcpServer() 

Source Link

Document

Create a TCP server with new selector pool of default size and a IoHandlerExecutor of default type ( OrderedHandlerExecutor )

Usage

From source file:com.semion.demo.mina.NioEchoServer.java

License:Apache License

public static void main(final String[] args) {
    LOG.info("starting echo server");

    final NioTcpServer acceptor = new NioTcpServer();

    // create the filter chain for this service
    acceptor.setFilters(new LoggingFilter("LoggingFilter1"));

    acceptor.setIoHandler(new AbstractIoHandler() {
        @Override/*  w w  w . j a  va  2  s  . c  om*/
        public void sessionOpened(final IoSession session) {
            LOG.info("session opened {}", session);

            final String welcomeStr = "welcome\n";
            final ByteBuffer bf = ByteBuffer.allocate(welcomeStr.length());
            bf.put(welcomeStr.getBytes());
            bf.flip();
            session.write(bf);
        }

        @Override
        public void messageReceived(IoSession session, Object message) {
            if (message instanceof ByteBuffer) {
                LOG.info("echoing");
                session.write(message);
            }
        }
    });
    try {
        final SocketAddress address = new InetSocketAddress(9999);
        acceptor.bind(address);
        LOG.debug("Running the server for 25 sec");
        Thread.sleep(25000);
        LOG.debug("Unbinding the TCP port");
        acceptor.unbind();
    } catch (final InterruptedException e) {
        LOG.error("Interrupted exception", e);
    }
}