|
| 1 | +package com.zhangjikai.socket; |
| 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 | + * Created by Jikai Zhang on 2017/5/13. |
| 14 | + */ |
| 15 | +public class SocketServer { |
| 16 | + |
| 17 | + public static void main(String[] args) throws IOException { |
| 18 | + String address = "localhost"; |
| 19 | + int port = 1234; |
| 20 | + ServerSocketChannel channel = ServerSocketChannel.open(); |
| 21 | + channel.socket().bind(new InetSocketAddress(address, port)); |
| 22 | + Selector selector = Selector.open(); |
| 23 | + channel.configureBlocking(false); |
| 24 | + channel.register(selector, SelectionKey.OP_ACCEPT); |
| 25 | + |
| 26 | + while (true) { |
| 27 | + selector.select(); |
| 28 | + Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); |
| 29 | + while (iterator.hasNext()) { |
| 30 | + SelectionKey key = iterator.next(); |
| 31 | + iterator.remove(); |
| 32 | + handleKey(key, selector); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + |
| 38 | + public static void handleKey(SelectionKey key, Selector selector) throws IOException { |
| 39 | + ServerSocketChannel server = null; |
| 40 | + SocketChannel client = null; |
| 41 | + if(key.isAcceptable()) { |
| 42 | + System.out.println("Acceptable"); |
| 43 | + server = (ServerSocketChannel) key.channel(); |
| 44 | + client = server.accept(); |
| 45 | + client.configureBlocking(false); |
| 46 | + client.register(selector, SelectionKey.OP_READ); |
| 47 | + } else if(key.isReadable()) { |
| 48 | + client = (SocketChannel) key.channel(); |
| 49 | + ByteBuffer byteBuffer = ByteBuffer.allocate(200); |
| 50 | + int count = client.read(byteBuffer); |
| 51 | + if(count > 0) { |
| 52 | + System.out.println("Readable"); |
| 53 | + System.out.println(new String(byteBuffer.array())); |
| 54 | + } else if(count == -1) { |
| 55 | + key.cancel(); |
| 56 | + return; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | +} |
0 commit comments