Echo Server via ServerSocketChannel - Java Network

Java examples for Network:Socket Channel

Description

Echo Server via ServerSocketChannel

Demo Code


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

public class NioEchoServer extends Thread {

    private static final int PORT_NUMBER = 6000;
    private static final long TIME_OUT = 3000;
    private ServerSocketChannel mServerChannel;
    private Selector mSelector;
    private boolean mLoop;

    ByteBuffer mBuf = ByteBuffer.allocate(8192);

    public NioEchoServer(int port) {
        SocketAddress isa = new InetSocketAddress(port);
        try {// w  w w.ja  va2 s  . c o m
            mServerChannel = ServerSocketChannel.open();
            mServerChannel.configureBlocking(false);
            ServerSocket s = mServerChannel.socket();

            s.bind(isa);
            mSelector = Selector.open();
            mServerChannel.register(mSelector, SelectionKey.OP_ACCEPT);
            mLoop = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        System.out.println("Waiting for connection from client.");
        try {
            while (mLoop) {
                int n = mSelector.select(TIME_OUT);
                if (n == 0)
                    continue;

                Set<SelectionKey> keys = mSelector.selectedKeys();
                Iterator<SelectionKey> it = keys.iterator();

                while (it.hasNext()) {
                    SelectionKey key = (SelectionKey) it.next();
                    if (!key.isValid())
                        continue;

                    if (key.isAcceptable()) {
                        acceptData(key);
                    } else if (key.isReadable()) {
                        processData(key);
                    }
                    it.remove();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void processData(SelectionKey key) throws IOException {
        if (key == null) {
            return;
        }

        SocketChannel channel = (SocketChannel) key.channel();
        mBuf.clear();
        int count = channel.read(mBuf);
        try {
            if (count < 0) {
                Socket socket = channel.socket();
                SocketAddress remoteAddr = socket.getRemoteSocketAddress();
                System.out.println(remoteAddr + " client: is shutdown.");
                channel.close();
                key.cancel();
                return;
            } else {
                mBuf.flip();
                byte[] receivedData = new byte[count];
                System.arraycopy(mBuf.array(), 0, receivedData, 0, count);
                String receivedStr = new String(receivedData);

                echo(channel, receivedStr);
                if (mBuf.remaining() > 0) {
                    key.selector().wakeup();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            key.channel().close();
            key.selector().wakeup();
        }

    }

    private void echo(SocketChannel channel, String receivedStr)
            throws IOException {
        mBuf.clear();
        mBuf.put(receivedStr.getBytes());
        mBuf.flip();
        channel.write(mBuf);

        System.out.println("server sends the message : " + receivedStr
                + " at" + new Date());

    }

    private void acceptData(SelectionKey key) throws IOException {
        ServerSocketChannel server = (ServerSocketChannel) key.channel();
        SocketChannel channel = server.accept();
        channel.configureBlocking(false);

        Socket socket = channel.socket();
        SocketAddress remoteAddr = socket.getRemoteSocketAddress();
        System.out.println("Connection opened client:" + remoteAddr);
        channel.register(mSelector, SelectionKey.OP_READ);

    }

    public static void main(String[] args) {
        int port = PORT_NUMBER;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }

        NioEchoServer server = new NioEchoServer(port);
        server.start();
        try {
            server.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void serversocket1() throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel server = ServerSocketChannel.open();

        ServerSocket socket = server.socket();
        SocketAddress address = new InetSocketAddress(5000);
        socket.bind(address);

        server.configureBlocking(false);
        server.register(selector, SelectionKey.OP_ACCEPT);

        ByteBuffer buf = ByteBuffer.allocate(1024);
        while (true) {
            try {
                selector.select();
            } catch (IOException e) {
            }
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iter = keys.iterator();
            while (iter.hasNext()) {
                SelectionKey selected = iter.next();

                iter.remove();

                SelectableChannel channel = selected.channel();
                if (channel instanceof ServerSocketChannel) {
                    ServerSocketChannel serverChannel = (ServerSocketChannel) channel;
                    SocketChannel socketChannel = serverChannel.accept();
                    if (socketChannel == null) {
                        continue;
                    }

                    socketChannel.configureBlocking(false);
                    int validOps = socketChannel.validOps();

                    socketChannel.register(selector, validOps);
                } else {
                    SocketChannel socketChannel = (SocketChannel) channel;

                }

            }
        }
    }

    private void serversocket2() throws IOException {
        ServerSocketChannel server = ServerSocketChannel.open();
        server.configureBlocking(true);
        server.socket().bind(new InetSocketAddress(5000));
        while (true) {
            SocketChannel sc = server.accept();
        }
    }

    private void serversocket3() throws IOException {

        Selector selector = Selector.open();
        ServerSocketChannel server = ServerSocketChannel.open();

        ServerSocket socket = server.socket();
        SocketAddress address = new InetSocketAddress(5000);
        socket.bind(address);

        server.configureBlocking(false);
        server.register(selector, SelectionKey.OP_ACCEPT);

        ByteBuffer buf = ByteBuffer.allocate(1024);
        while (true) {
            try {
                selector.select();
            } catch (IOException e) {
            }
            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iter = keys.iterator();
            while (iter.hasNext()) {
                SelectionKey selected = iter.next();

                iter.remove();

                SelectableChannel channel = selected.channel();
                if (channel instanceof ServerSocketChannel) {
                    ServerSocketChannel serverChannel = (ServerSocketChannel) channel;
                    SocketChannel socketChannel = serverChannel.accept();
                    if (socketChannel == null) {
                        continue;
                    }

                    socketChannel.configureBlocking(false);
                    int validOps = socketChannel.validOps();

                    socketChannel.register(selector, validOps);
                } else {
                    SocketChannel socketChannel = (SocketChannel) channel;
                    socketChannel.configureBlocking(true);
                    new NewThread(socketChannel).start();
                }

            }
        }
    }

    class NewThread extends Thread {

        private SocketChannel channel;

        public NewThread(SocketChannel socketChannel) {
            this.channel = socketChannel;
        }

        @Override
        public void run() {
            OutputStream oos = Channels.newOutputStream(channel);
            InputStream ins = Channels.newInputStream(channel);
            try (InputStreamReader is = new InputStreamReader(ins, "utf-8");
                    BufferedReader in = new BufferedReader(is)) {
                String res = in.readLine();
                while (!"".equals(res)) {
                    System.out.println(res);
                    res = in.readLine();
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

}

Related Tutorials