Skip to content

Commit

Permalink
JAVA NIO SELECT INIT
Browse files Browse the repository at this point in the history
  • Loading branch information
OomelodyoO authored and OomelodyoO committed Sep 10, 2018
1 parent dc5a642 commit 85ac910
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions nio/src/main/java/win/zhang/select/SelectServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package win.zhang.select;

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 SelectServer {
public static void main(String[] args) throws IOException {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);
Selector selector = Selector.open();
SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
int select = selector.select();
if (select > 0) {
Iterator keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
SelectionKey next = (SelectionKey) keyIterator.next();
keyIterator.remove();
if (next.isAcceptable()) {
System.out.println("isAcceptable");
SocketChannel channel = ((ServerSocketChannel) next.channel()).accept();
channel.configureBlocking(false);
channel.register(selector, SelectionKey.OP_READ);
} else if (next.isConnectable()) {
System.out.println("connect");
} else if (next.isReadable()) {
System.out.println("isReadable");
SocketChannel socketChannel = (SocketChannel) next.channel();
ByteBuffer readByteBuffer = ByteBuffer.allocate(100);
int read = socketChannel.read(readByteBuffer);
System.out.println(new String(readByteBuffer.array(), 0, read));
socketChannel.register(selector, SelectionKey.OP_WRITE);
socketChannel.write(readByteBuffer);
} else if (next.isWritable()) {
System.out.println("isWritable");
SocketChannel socketChannel = (SocketChannel) next.channel();
socketChannel.register(selector, SelectionKey.OP_READ);
}
}
}
}
}
}

0 comments on commit 85ac910

Please sign in to comment.