NIO 笔记

package tk.andrew.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;
import java.util.Set;

/**
 * @author dafuchen
 *         2018/1/31
 */
public class Server {
    private static final int SIZE = 1024;
    public static void main(String[] args) {
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            Selector selector = Selector.open()) {
            // 绑定端口号
            serverSocketChannel.socket().bind(new InetSocketAddress( 8080));
            // 设置为非阻塞的
            serverSocketChannel.configureBlocking(false);
            // 把这个socket 设置为accetp
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            while (true) {
                Thread.sleep(1000L);
                // 在没有新的请求的时候 程序会阻塞在这个地方
                selector.select();
                // 每一次都会尝试去获得该次遍历中活跃的key
                // 是selectedKeys(); 而不是keys()
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
                while(selectionKeyIterator.hasNext()) {
                    SelectionKey selectionKey = selectionKeyIterator.next();
                    selectionKeyIterator.remove();
                    if (selectionKey.isValid()) {
                    // 是否TCP 三次连接是否已经准备好
                        if (selectionKey.isAcceptable()) {
                            ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
                            SocketChannel socketChannel = ssc.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.write(ByteBuffer.wrap(new String("send a message from server").getBytes()));
                            // SelectionKey类型的设置非常的重要
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }

                        if (selectionKey.isReadable()) {
                            SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(SIZE);
                            int size = socketChannel.read(byteBuffer);
                            if (size >= 0) {
                                byte[] data = byteBuffer.array();
                                String msg = new String(data).trim();
                                System.out.println(msg);
                                socketChannel.write(ByteBuffer.wrap(new String("send a message from server").getBytes()));
                            } else {
                                socketChannel.close();
                                selectionKey.cancel();
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
package tk.andrew.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;

/**
 * @author dafuchen
 *         2018/2/1
 */
public class Client {
    private static final int SIZE = 1024;
    private static final String IP_ADDRESS = "127.0.0.1";
    private static final int PORT = 8080;
    public static void main(String[] args) throws IOException, InterruptedException {
        SocketChannel socketChannel = SocketChannel.open();
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        // 注意 这里是connect 而不是bind
        socketChannel.connect(new InetSocketAddress(IP_ADDRESS, PORT));
        // 注意这里的类型是 OP_CONNECT 而不是OP_ACCEPT
        socketChannel.register(selector, SelectionKey.OP_CONNECT);

        while(true) {
        // 每一次都会尝试获得在该次遍历中活跃的key
        // 是selectKeys 而不是 keys()
            Thread.sleep(1000);
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                iterator.remove();
                if (selectionKey.isValid()) {
                    if (selectionKey.isConnectable()) {
                        SocketChannel sc = (SocketChannel) selectionKey.channel();
                        if (sc.isConnectionPending()) {
                            sc.finishConnect();
                        }
                        sc.configureBlocking(false);
                        sc.write(ByteBuffer.wrap(new String("向服务端发送了一条信息").getBytes()));
                        sc.register(selector, SelectionKey.OP_READ);
                    } else {
                        if (selectionKey.isReadable()) {
                            SocketChannel sc = (SocketChannel) selectionKey.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(SIZE);
                            int size = sc.read(byteBuffer);
                            if (size >= 0) {
                                byte[] data = byteBuffer.array();
                                String msg = new String(data).trim();
                                System.out.println(msg);
                                sc.write(ByteBuffer.wrap(new String("向服务端发送了一条信息").getBytes()));
                            } else {
                                sc.close();
                                selectionKey.channel();
                            }
                        }
                    }
                }
            }
        }
    }
}

代码抄袭自[NIO与传统IO的区别]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值