-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTest.java
More file actions
58 lines (47 loc) · 1.63 KB
/
Test.java
File metadata and controls
58 lines (47 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package NIO;
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;
import java.util.Set;
public class Test {
public void selector() throws IOException {
ByteBuffer buffer=ByteBuffer.allocate(1024);
Selector selector=Selector.open();
ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);//设为非阻塞方式
serverSocketChannel.socket().bind(new InetSocketAddress(8080));
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while(true) {
Set selectedKeys=selector.selectedKeys();
Iterator iterator=selectedKeys.iterator();
while(iterator.hasNext()) {
SelectionKey key=(SelectionKey) iterator.next();
if((key.readyOps()&SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT) {
ServerSocketChannel ssChannel=(ServerSocketChannel) key.channel();
SocketChannel sc=ssChannel.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
iterator.remove();
}else if((key.readyOps() & SelectionKey.OP_ACCEPT)==SelectionKey.OP_READ) {
SocketChannel sc=(SocketChannel) key.channel();
while(true) {
buffer.clear();
int n=sc.read(buffer);
if(n<=0) {
break;
}
buffer.flip();
}
iterator.remove();
}
}
}
}
public static void main(String[] args) {
}
}