JAVA NIO

参考文章:

http://weixiaolu.iteye.com/blog/1479656

http://developer.51cto.com/art/201112/307463.htm

NIO服务端

package com.meso.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOServer {
    private ServerSocketChannel serverChannel;
    private Selector selector;
    private int port;

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

    public void initServer() throws IOException {
        System.out.println("开始初始化服务端");

        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.socket().bind(new InetSocketAddress(port));

        selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        System.out.println("服务端初始化完毕");
    }

    public void listen() throws IOException {
        System.out.println("开始监听");
        while (true) {
            int num = selector.select();
            System.out.println("新事件数目:" + num);

            Iterator it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey) it.next();
                it.remove();

                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key
                            .channel();
                    SocketChannel channel = server.accept();
                    channel.configureBlocking(false);
                    channel.write(ByteBuffer.wrap(new String("向客户端发送了一条信息")
                            .getBytes()));
                    channel.register(this.selector, SelectionKey.OP_READ);

                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);

                    buffer.clear();
                    channel.read(buffer);
                    String msg = new String(buffer.array()).trim();
                    System.out.println("服务端收到信息:" + msg);

                    buffer.flip();
                    channel.write(buffer);
                }
            }
        }
    }

    public void close() {
        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (serverChannel != null) {
            try {
                serverChannel.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        NIOServer server = new NIOServer(9999);
        try {
            server.initServer();
            server.listen();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            server.close();
        }
    }
}

NIO客户端

package com.meso.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOClient {
    private Selector selector;
    private SocketChannel channel;

    private String ip;
    private int port;

    public NIOClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void initClient() throws IOException {
        System.out.println("客户端开始初始化");

        channel = SocketChannel.open();
        channel.configureBlocking(false);
        this.selector = Selector.open();

        channel.connect(new InetSocketAddress(ip, port));
        channel.register(selector, SelectionKey.OP_CONNECT);

        System.out.println("客户端初始化完毕");
    }

    public void listen() throws IOException {
        System.out.println("开始监听");

        while (true) {
            int num = selector.select();
            System.out.println("新事件数目:" + num);

            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                ite.remove();
                if (key.isConnectable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    if (channel.isConnectionPending()) {
                        channel.finishConnect();

                    }
                    channel.configureBlocking(false);

                    channel.write(ByteBuffer.wrap(new String("向服务端发送了一条信息")
                            .getBytes()));
                    channel.register(this.selector, SelectionKey.OP_READ);

                } else if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(100);

                    buffer.clear();
                    channel.read(buffer);
                    String msg = new String(buffer.array()).trim();
                    System.out.println("客户端收到信息:" + msg);

                    buffer.flip();
                    channel.write(buffer);
                }

            }

        }
    }

    public void close() {
        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        NIOClient client = new NIOClient("localhost", 9999);
        try {
            client.initClient();
            client.listen();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            client.close();
        }
    }
}
原文地址:https://www.cnblogs.com/xiaominghupan/p/4245817.html