服务器端

/**
 * 功能描述: 基于NIO(非线程阻塞)实现的网络聊天室服务端<br>
 *
 * @since: 1.0.0
 * @Author:薛向毅
 */
public class ChatRoomServer {

    private Selector selector = null;
    static final int port = 8089;
    private Charset charset = Charset.forName("UTF-8");
    //用来记录在线人数,以及昵称
    private static HashSet<String> users = new HashSet<String>();

    private static String USER_EXIST = "system message: user exist, please change a name";
    //相当于自定义协议格式,与客户端协商好
    private static String USER_CONTENT_SPILIT = ":";

    private static boolean flag = false;

    public void init() throws IOException {
        selector = Selector.open();//打开一个通道选择器
        //打开一个通道
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        //设置为非阻塞的方式
        serverChannel.configureBlocking(false);
        serverChannel.bind(new InetSocketAddress(port));
        //注册到选择器,权限为  接收数据
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("Server is listening now...");


        //
        while (true) {
            int readyChannels = selector.select();//获得所有的通道
            if (readyChannels == 0) continue;//如果没有就跳出循环
            Set<SelectionKey> selectionKeys = selector.selectedKeys();//获取可用的通道的集合
            //通过迭代器,迭代可用的通道
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey sk = keyIterator.next();
                keyIterator.remove();//
                //根据选择键,判断channel的方式
                dealWithSelectionKey(serverChannel, sk);
            }

        }

    }


    public void dealWithSelectionKey(ServerSocketChannel serverChannel, SelectionKey sk) throws IOException {
        //如果是接收的通道
        if (sk.isAcceptable()) {
            SocketChannel sc = serverChannel.accept();
            //使用非阻塞模式
            sc.configureBlocking(false);
            //注册选择器,设置为读取模式,收到一个连接请求,然后起一个SocketChannel,并注册到selector上,之后这个连接的数据,就由这个SocketChannel处理
            sc.register(selector, SelectionKey.OP_READ);

            //将对应的channel设置为准备接收其他客户端的请求
            sk.interestOps(SelectionKey.OP_ACCEPT);
            System.out.println("Server is listening from client :" + sc.getRemoteAddress());
            sc.write(Charset.forName("UTF-8").encode("请输入你的名字:"));
        }
        //处理来自客户端的数据读取请求
        if (sk.isReadable()) {
            //返回该selectionKey对应的Channel,其中有数据需要读取
            //返回该SelectionKey对应的 Channel,其中有数据需要读取
            SocketChannel sc = (SocketChannel) sk.channel();
            ByteBuffer buff = ByteBuffer.allocate(1024);
            StringBuilder content = new StringBuilder();
            try {
                while (sc.read(buff) > 0) {
                    buff.flip();
                    content.append(charset.decode(buff));

                }
                System.out.println("Server is listening from client " + sc.getRemoteAddress() + " data rev is: " + content);
                //将此对应的channel设置为准备下一次接受数据
                sk.interestOps(SelectionKey.OP_READ);
            } catch (IOException io) {
                sk.cancel();
                if (sk.channel() != null) {
                    sk.channel().close();
                }
            }
            if (content.length() > 0) {
                String[] arrayContent = content.toString().split(USER_CONTENT_SPILIT);
                //注册用户
                if (arrayContent != null && arrayContent.length == 1) {
                    String name = arrayContent[0];
                    if (users.contains(name)) {
                        sc.write(charset.encode(USER_EXIST));

                    } else {
                        users.add(name);
                        int num = OnlineNum(selector);
                        String message = "welcome " + name + " to chat room! Online numbers:" + num;
                        BroadCast(selector, null, message);
                    }
                }
                //注册完了,发送消息
                else if (arrayContent != null && arrayContent.length > 1) {
                    String name = arrayContent[0];
                    String message = content.substring(name.length() + USER_CONTENT_SPILIT.length());
                    message = name + " say " + message;
                    if (users.contains(name)) {
                        //不回发给发送此内容的客户端
                        BroadCast(selector, sc, message);
                    }
                }
            }

        }
    }

    //TODO 要是能检测下线,就不用这么统计了
    public static int OnlineNum(Selector selector) {
        int res = 0;
        for (SelectionKey key : selector.keys()) {
            Channel targetchannel = key.channel();

            if (targetchannel instanceof SocketChannel) {
                res++;
            }
        }
        return res;
    }

    public void BroadCast(Selector selector, SocketChannel except, String content) throws IOException {
        //广播数据到所有的SocketChannel中
        for (SelectionKey key : selector.keys()) {
            Channel targetchannel = key.channel();
            //如果except不为空,不回发给发送此内容的客户端
            if (targetchannel instanceof SocketChannel && targetchannel != except) {
                SocketChannel dest = (SocketChannel) targetchannel;
                dest.write(charset.encode(content));
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new ChatRoomServer().init();
    }


}

客户端

/**
 * @author 薛向毅
 * @create 2018-05-25
 10:06
 **/
public class ChatRoomClient {
    private Selector selector = null;
    static final int port = 8089;
    private Charset charset = Charset.forName("UTF-8");
    private SocketChannel sc = null;
    private String name = "";
    private static String USER_EXIST = "用户名已经存在,请重新写一个吧";
    private static String USER_CONTENT_SPILIT = ":";

    public void init() throws IOException {
        selector = Selector.open();
        //连接远程主机的IP和端口
        sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", port));
        sc.configureBlocking(false);
        sc.register(selector, SelectionKey.OP_READ);
        //开辟一个新线程来读取从服务器端的数据s
        new Thread(new ClientThread()).start();
        //在主线程中 从键盘读取数据输入到服务器端
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            if ("".equals(line)) continue; //不允许发空消息
            if ("".equals(name)) {
                name = line;
                line = name + USER_CONTENT_SPILIT;
            } else {
                line = name + USER_CONTENT_SPILIT + line;
            }
            sc.write(charset.encode(line));//sc既能写也能读,这边是写
        }

    }

    private class ClientThread implements Runnable {
        public void run() {
            try {
                while (true) {
                    int readyChannels = selector.select();
                    if (readyChannels == 0) continue;
                    Set selectedKeys = selector.selectedKeys();  //可以通过这个方法,知道可用通道的集合
                    Iterator keyIterator = selectedKeys.iterator();
                    while (keyIterator.hasNext()) {
                        SelectionKey sk = (SelectionKey) keyIterator.next();
                        keyIterator.remove();
                        dealWithSelectionKey(sk);
                    }
                }
            } catch (IOException io) {
            }
        }

        private void dealWithSelectionKey(SelectionKey sk) throws IOException {
            if (sk.isReadable()) {
                //使用 NIO 读取 Channel中的数据,这个和全局变量sc是一样的,因为只注册了一个SocketChannel
                //sc既能写也能读,这边是读
                SocketChannel sc = (SocketChannel) sk.channel();

                ByteBuffer buff = ByteBuffer.allocate(1024);
                String content = "";
                while (sc.read(buff) > 0) {
                    buff.flip();
                    content += charset.decode(buff);
                }
                //若系统发送通知名字已经存在,则需要换个昵称
                if (USER_EXIST.equals(content)) {
                    name = "";
                }
                System.out.println(content);
                sk.interestOps(SelectionKey.OP_READ);
            }
        }
    }


    public static void main(String[] args) throws IOException {
        new ChatRoomClient().init();


    }
}