NIO中异步IO的完整实现实例
来源:互联网 发布:2014网络女歌手名字 编辑:程序博客网 时间:2024/05/22 14:59
重点是Selector这个类,测试时,启动后,远程登录监听的端口
public class SelectSockets {public static int PORT_NUMBER = 1234;public static void main(String[] argv) throws Exception {new SelectSockets().go(argv);}public void go(String[] argv) throws Exception {int port = PORT_NUMBER;if (argv.length > 0) { // override default listen portport = Integer.parseInt(argv[0]);}System.out.println("Listening on port " + port);// allocate an unbound server socket channelServerSocketChannel serverChannel = ServerSocketChannel.open();// Get the associated ServerSocket to bind it withServerSocket serverSocket = serverChannel.socket();// set the port the server channel will listen toserverSocket.bind(new InetSocketAddress(port));// set non-blocking mode for the listening socketserverChannel.configureBlocking(false);// create a new Selector for use belowSelector selector = Selector.open();// register the ServerSocketChannel with the SelectorserverChannel.register(selector, SelectionKey.OP_ACCEPT);while (true) {// this may block for a long time, upon return the// selected set contains keys of the ready channelsint n = selector.select();if (n == 0) {continue; // nothing to do}// get an iterator over the set of selected keysIterator it = selector.selectedKeys().iterator();// look at each key in the selected setwhile (it.hasNext()) {SelectionKey key = (SelectionKey) it.next();// Is a new connection coming in?if (key.isAcceptable()) {ServerSocketChannel server = (ServerSocketChannel) key.channel();SocketChannel channel = server.accept();registerChannel(selector, channel, SelectionKey.OP_READ);sayHello(channel);}// is there data to read on this channel?if (key.isReadable()) {readDataFromSocket(key);}// remove key from selected set, it's been handledit.remove();}}}// ----------------------------------------------------------/** * Register the given channel with the given selector for the given * operations of interest */protected void registerChannel(Selector selector, SelectableChannel channel, int ops)throws Exception {if (channel == null) {return; // could happen}// set the new channel non-blockingchannel.configureBlocking(false);// register it with the selectorchannel.register(selector, ops);}// ----------------------------------------------------------// Use the same byte buffer for all channels. A single thread is// servicing all the channels, so no danger of concurrent acccess.private ByteBuffer buffer = ByteBuffer.allocateDirect(1024);/** * Sample data handler method for a channel with data ready to read. * * @param key * A SelectionKey object associated with a channel determined by * the selector to be ready for reading. If the channel returns * an EOF condition, it is closed here, which automatically * invalidates the associated key. The selector will then * de-register the channel on the next select call. */protected void readDataFromSocket(SelectionKey key) throws Exception {SocketChannel socketChannel = (SocketChannel) key.channel();int count;buffer.clear(); // make buffer empty// loop while data available, channel is non-blockingwhile ((count = socketChannel.read(buffer)) > 0) {buffer.flip(); // make buffer readable// send the data, don't assume it goes all at oncewhile (buffer.hasRemaining()) {socketChannel.write(buffer);}// WARNING: the above loop is evil. Because// it's writing back to the same non-blocking// channel it read the data from, this code can// potentially spin in a busy loop. In real life// you'd do something more useful than this.buffer.clear(); // make buffer empty}if (count < 0) {// close channel on EOF, invalidates the keysocketChannel.close();}}// ----------------------------------------------------------/** * Spew a greeting to the incoming client connection. * * @param channel * The newly connected SocketChannel to say hello to. */private void sayHello(SocketChannel channel) throws Exception {buffer.clear();buffer.put("Hi there!\r\n".getBytes());buffer.flip();channel.write(buffer);}}
- NIO中异步IO的完整实现实例
- 二、基于BIO、伪异步IO、NIO的Java代码实例
- Java NIO 新型的异步IO方法
- Java中网络IO的实现方式-BIO、NIO、AIO
- NIO与传统IO的区别 NIO Socket例子 实例
- NIO与传统IO的区别 NIO Socket例子 实例
- NIO与传统IO的区别 NIO Socket例子 实例
- 一个异步io中同步调用close造成数据传输不完整的bug。
- nio异步io的将来式和回调式
- nodejs异步IO的实现
- 9 异步io的实现
- Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
- Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
- Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
- Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
- Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
- Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
- Java网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
- 多target iphone
- Linux平台上如何使用接静态库和共享库
- iphone 实现截屏的函数
- IPhone开发中的HTTP链接问题
- 消息称电信将于10月引入两款CDMA版iPhone
- NIO中异步IO的完整实现实例
- 研究牛人的程序struct-dump.h
- 黑马程序员--javaAPI
- linux查看硬件信息及驱动设备相关整理(留存验证)
- Android 获取自己程序APK包的MD5指纹
- DWR的异常处理及session过期
- Ubuntu桌面版讨论使用全局菜单和取消的命令
- 入侵软件学习
- sql 连接字符串大全