1 package rodking.server;
2
3 import java.io.IOException;
4 import java.net.InetSocketAddress;
5 import java.nio.ByteBuffer;
6 import java.nio.channels.SelectionKey;
7 import java.nio.channels.Selector;
8 import java.nio.channels.ServerSocketChannel;
9 import java.nio.channels.SocketChannel;
10 import java.util.Iterator;
11
12 /**
13 * @author rodking
14 * @des 非阻塞的通信
15 */
16 public class NIOServer {
17 private Selector selector;
18
19 public void initServer(int port) throws IOException {
20 ServerSocketChannel serverChannel = ServerSocketChannel.open();
21 // 设置为非阻塞模式
22 serverChannel.configureBlocking(false);
23 serverChannel.socket().bind(new InetSocketAddress(port));
24 this.selector = Selector.open();
25
26 serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
27 }
28
29 public void lisiten() throws IOException {
30 System.out.println("Server Start...");
31 while (true) {
32 selector.select();
33 Iterator<?> it = selector.selectedKeys().iterator();
34 while (it.hasNext()) {
35 SelectionKey key = (SelectionKey) it.next();
36 it.remove();
37 if (key.isAcceptable()) {
38 ServerSocketChannel server = (ServerSocketChannel) key.channel();
39 SocketChannel channel = server.accept();
40 channel.configureBlocking(false);
41 channel.write(ByteBuffer.wrap(new String("you giv me a message").getBytes()));
42
43 channel.register(selector, SelectionKey.OP_READ);
44
45 } else if (key.isReadable()) {
46 read(key);
47 }
48
49 }
50 }
51 }
52
53 private void read(SelectionKey key) throws IOException {
54 SocketChannel channel = (SocketChannel) key.channel();
55 ByteBuffer buf = ByteBuffer.allocate(10);
56 channel.read(buf);
57 byte[] data = buf.array();
58 String str = new String(data).trim();
59 System.out.println(" received message " + str);
60 ByteBuffer outBuf = ByteBuffer.wrap(str.getBytes());
61 channel.write(outBuf);
62 }
63
64 public static void main(String[] args) throws IOException {
65 NIOServer nioServer = new NIOServer();
66 nioServer.initServer(9000);
67 nioServer.lisiten();
68 }
69 }