-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- 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.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |