003 NIO实现简单的服务和用户

package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NSer {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.socket().bind(new InetSocketAddress(3333));
        socketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_ACCEPT);

        int count = 1;
        while (true) {
            if (selector.select(1000) == 0) {
                System.out.println("wait----------------:"+count++);
            }else {
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();

                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        SocketChannel sock = socketChannel.accept();
                        sock.configureBlocking(false);
                        System.out.println("sock = " + sock.hashCode());
                        sock.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1234));
                    }
                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer);
                        System.out.println(new String(buffer.array(),0,read));
                    }
                    iterator.remove();
                }
            }
        }



    }
}

package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NCli {
    public static void main(String[] args) throws Exception {
        InetSocketAddress remote = new InetSocketAddress("127.0.0.1", 3333);
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        if (!channel.connect(remote)) {
            while (!channel.finishConnect()){
                System.out.println("i need time---------------------");
            }
        }

        ByteBuffer buf = ByteBuffer.wrap("i am coming".getBytes());
        channel.write(buf);
        System.in.read();

    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值