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.Date; import java.util.Iterator; import java.util.Set; /** * Created by mapan on 2014/8/18. */ public class NioServer { Selector selector = null; public NioServer(int port) throws IOException { selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(port)); serverSocketChannel.configureBlocking(false); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); } public void handle() throws IOException { while (!Thread.interrupted()) { selector.select(); Set<SelectionKey> selectionKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = selectionKeys.iterator(); while (iterator.hasNext()) { SelectionKey next = iterator.next(); iterator.remove(); if (next.isAcceptable()) { ServerSocketChannel channel = (ServerSocketChannel) next.channel(); SocketChannel accept = channel.accept(); accept.configureBlocking(false); accept.register(selector, SelectionKey.OP_READ); }else if (next.isReadable()) { SocketChannel channel = (SocketChannel) next.channel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); int read = channel.read(byteBuffer); String readString = new String(byteBuffer.array(), 0, read).trim(); System.out.println(readString); if (readString.equals("quit")) { channel.close(); } else { // 這裏也能夠不用 下面一句話註冊寫事件,直接經過 channel.write() 去給客戶端返回數據 channel.register(selector, SelectionKey.OP_WRITE); } }else if (next.isWritable()) { String date = (new Date()).toString() + "\r\n"; SocketChannel channel = (SocketChannel) next.channel(); channel.write(ByteBuffer.wrap(date.getBytes())); next.interestOps(SelectionKey.OP_READ); } } } } public static void main(String[] args) throws IOException { NioServer nioServer = new NioServer(9999); nioServer.handle(); } }
說明:java
再nio socket中,打開的是雙向通道,若是 創建鏈接之後,是直接能夠寫的:寫的代碼以下:socket
channel.write()
可是這個在nio socket裏面是不推薦的,建議仍是經過註冊相應的寫事件,向客戶端返回數據。ui
這個只是簡單的一個 nio socket的事例代碼。.net