-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
64 changes: 64 additions & 0 deletions
64
java-io/src/main/java/com/brianway/learning/java/nio/tutorial/SelectorDemo.java
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,64 @@ | ||
package com.brianway.learning.java.nio.tutorial; | ||
|
||
import java.io.IOException; | ||
import java.net.InetSocketAddress; | ||
import java.nio.channels.SelectionKey; | ||
import java.nio.channels.Selector; | ||
import java.nio.channels.ServerSocketChannel; | ||
import java.util.Iterator; | ||
import java.util.Set; | ||
|
||
/** | ||
* Full Selector Example | ||
* 启动后,浏览器输入 localhost:9999 | ||
* | ||
* @auther brian | ||
* @since 2019/6/24 22:29 | ||
*/ | ||
public class SelectorDemo { | ||
|
||
public static void main(String[] args) throws IOException { | ||
Selector selector = Selector.open(); | ||
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); | ||
serverSocketChannel.socket().bind(new InetSocketAddress(9999)); | ||
serverSocketChannel.configureBlocking(false); | ||
|
||
// SelectionKey key = | ||
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); | ||
|
||
while (true) { | ||
|
||
int readyChannels = selector.selectNow(); | ||
|
||
if (readyChannels == 0) { | ||
// System.out.println("readyChannels == 0"); | ||
continue; | ||
} | ||
|
||
Set<SelectionKey> selectedKeys = selector.selectedKeys(); | ||
|
||
Iterator<SelectionKey> keyIterator = selectedKeys.iterator(); | ||
|
||
while (keyIterator.hasNext()) { | ||
|
||
SelectionKey key = keyIterator.next(); | ||
|
||
if (key.isAcceptable()) { | ||
// a connection was accepted by a ServerSocketChannel. | ||
System.out.println("accepted"); | ||
} else if (key.isConnectable()) { | ||
// a connection was established with a remote server. | ||
System.out.println("connectable"); | ||
} else if (key.isReadable()) { | ||
// a channel is ready for reading | ||
System.out.println("ready"); | ||
} else if (key.isWritable()) { | ||
// a channel is ready for writing | ||
System.out.println("writable"); | ||
} | ||
|
||
keyIterator.remove(); | ||
} | ||
} | ||
} | ||
} |