-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNIO.java
More file actions
48 lines (45 loc) · 1.76 KB
/
Copy pathNIO.java
File metadata and controls
48 lines (45 loc) · 1.76 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
package IO;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
public class NIO {
static ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
static List<SocketChannel> channelList = new ArrayList<>();
public static void main(String[] args) {
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
SocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 8098);
serverSocketChannel.bind(socketAddress);
serverSocketChannel.configureBlocking(false);
while (true) {
for (SocketChannel socketChannel : channelList
) {
int read = socketChannel.read(byteBuffer);
if (read > 0) {
System.out.println("read---- ");
byteBuffer.flip();
byte[] bs = new byte[read];
byteBuffer.get(bs);
String content = new String(bs);
System.out.println(content);
byteBuffer.flip();
}
}
SocketChannel accept = serverSocketChannel.accept();
if (accept != null) {
System.out.println("conn success");
accept.configureBlocking(false);
channelList.add(accept);
System.out.println(channelList.size() + "list --size");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}