0
|
1 import java.io.IOException;
|
|
2 import java.net.InetSocketAddress;
|
|
3 import java.nio.channels.SelectionKey;
|
|
4 import java.nio.channels.Selector;
|
|
5 import java.nio.channels.ServerSocketChannel;
|
|
6
|
|
7 public class WebSocketServer {
|
|
8 public static int port;
|
|
9 private ServerSocketChannel ssChannel;
|
|
10 private Selector selector;
|
|
11 private boolean running = true;
|
|
12
|
|
13 public WebSocketServer(int port) {
|
|
14 this.port = port;
|
|
15 try {
|
|
16 ssChannel = ServerSocketChannel.open();
|
|
17 ssChannel.socket().bind(new InetSocketAddress(port));
|
|
18 ssChannel.configureBlocking(false);
|
|
19 selector = Selector.open();
|
|
20 ssChannel.register(selector, SelectionKey.OP_ACCEPT, new AcceptHandler());
|
|
21 } catch (IOException e) {
|
|
22 System.out.println("Can't open ServerSocketChannel.");
|
|
23 e.printStackTrace();
|
|
24 }
|
|
25 }
|
|
26
|
|
27 public void mainLoop() {
|
|
28
|
|
29 while (running) {
|
|
30 try {
|
|
31 int keyCount = selector.select(0);
|
|
32 for (SelectionKey key : selector.selectedKeys()) {
|
|
33 Handler handler = (Handler) key.attachment();
|
|
34 handler.handle(key);
|
2
|
35 // selector.selectedKeys().remove(key);
|
0
|
36 }
|
2
|
37 selector.selectedKeys().clear();
|
0
|
38
|
|
39 } catch (IOException e) {
|
|
40 e.printStackTrace();
|
|
41 }
|
|
42 }
|
|
43
|
|
44 }
|
|
45
|
|
46 /**
|
|
47 * @param args
|
|
48 */
|
|
49 public static void main(String[] args) {
|
|
50 WebSocketServer wsServer = new WebSocketServer(11000);
|
|
51 wsServer.mainLoop();
|
|
52 }
|
|
53
|
|
54 }
|