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

    技术2022-07-13  63

    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(); } }
    Processed: 0.009, SQL: 9