`
dodoflying
  • 浏览: 176347 次
社区版块
存档分类
最新评论
阅读更多
今天研究了NIO(New IO)API上的几个例子代码,并且做了测试。
TimeQuery.java是一个利用NIO进行查询当前主机时间的客户端代码
/*
 * @(#);TimeQuery.java	1.2 01/12/13
 * Ask a list of hosts what time it is.  Demonstrates NIO socket channels
 * (connection and reading);, buffer handling, charsets, and regular
 * expressions.
 *
 * Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or 
 * without modification, are permitted provided that the following 
 * conditions are met:
 * 
 * -Redistributions of source code must retain the above copyright  
 * notice, this  list of conditions and the following disclaimer.
 * 
 * -Redistribution in binary form must reproduct the above copyright 
 * notice, this list of conditions and the following disclaimer in 
 * the documentation and/or other materials provided with the 
 * distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of 
 * contributors may be used to endorse or promote products derived 
 * from this software without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any 
 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND 
 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY 
 * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY 
 * DAMAGES OR LIABILITIES  SUFFERED BY LICENSEE AS A RESULT OF  OR 
 * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR 
 * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE 
 * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, 
 * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER 
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF 
 * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that Software is not designed, licensed or 
 * intended for use in the design, construction, operation or 
 * maintenance of any nuclear facility. 
 */

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.regex.*;


public class TimeQuery {

    // The standard daytime port
    private static int DAYTIME_PORT = 13;

    // The port we'll actually use
    private static int port = DAYTIME_PORT;

    // Charset and decoder for US-ASCII
    private static Charset charset = Charset.forName("US-ASCII");;
    private static CharsetDecoder decoder = charset.newDecoder();;

    // Direct byte buffer for reading
    private static ByteBuffer dbuf = ByteBuffer.allocateDirect(1024);;

    // Ask the given host what time it is
    //
    private static void query(String host); throws IOException {
	InetSocketAddress isa
	    = new InetSocketAddress(InetAddress.getByName(host);, port);;
	SocketChannel sc = null;

	try {

	    // Connect
	    sc = SocketChannel.open();;
	    sc.connect(isa);;

	    // Read the time from the remote host.  For simplicity we assume
	    // that the time comes back to us in a single packet, so that we
	    // only need to read once.
/*
clear
public final Buffer clear();
Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. 
Invoke this method before using a sequence of channel-read or put operations to fill this buffer. For example: 

 buf.clear();;     // Prepare buffer for reading
 in.read(buf);;    // Read data
This method does not actually erase the data in the buffer, but it is named as if it did because it will most often be used in situations in which that might as well be the case. 


Returns:
This buffer
*/
	    dbuf.clear();;    
	    sc.read(dbuf);;

	    // Print the remote address and the received time
/*
public final Buffer flip();
Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. 
After a sequence of channel-read or put operations, invoke this method to prepare for a sequence of channel-write or relative get operations. For example: 

 buf.put(magic);;    // Prepend header
 in.read(buf);;      // Read data into rest of buffer
 buf.flip();;        // Flip buffer
 out.write(buf);;    // Write header + data to channel
This method is often used in conjunction with the compact method when transferring data from one place to another. 


Returns:
This buffer
*/
	    dbuf.flip();;
	    CharBuffer cb = decoder.decode(dbuf);;
	    System.out.print(isa + " : " + cb);;

	} finally {
	    // Make sure we close the channel (and hence the socket);
	    if (sc != null);
		sc.close();;
	}
    }

    public static void main(String[] args); {
	if (args.length < 1); {
	    System.err.println("Usage: java TimeQuery [port] host...");;
	    return;
	}
	int firstArg = 0;

	// If the first argument is a string of digits then we take that
	// to be the port number
	if (Pattern.matches("[0-9]+", args[0]);); {
	    port = Integer.parseInt(args[0]);;
	    firstArg = 1;
	}

	for (int i = firstArg; i < args.length; i++); {
	    String host = args[i];
	    try {
		query(host);;
	    } catch (IOException x); {
		System.err.println(host + ": " + x);;
	    }
	}
    }

}



NBTimeServer.java 实现了一个非阻塞的网络时间查询服务器
/*
 * @(#);NBTimeServer.java	1.4 01/12/13
 * A non blocking Internet time server implemented using
 * the New I/O (NIO); facilities added to J2SE v 1.4.
 *
 * Copyright 2001-2002 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or 
 * without modification, are permitted provided that the following 
 * conditions are met:
 * 
 * -Redistributions of source code must retain the above copyright  
 * notice, this  list of conditions and the following disclaimer.
 * 
 * -Redistribution in binary form must reproduct the above copyright 
 * notice, this list of conditions and the following disclaimer in 
 * the documentation and/or other materials provided with the 
 * distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of 
 * contributors may be used to endorse or promote products derived 
 * from this software without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any 
 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND 
 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY 
 * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY 
 * DAMAGES OR LIABILITIES  SUFFERED BY LICENSEE AS A RESULT OF  OR 
 * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR 
 * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE 
 * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, 
 * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER 
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF 
 * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that Software is not designed, licensed or 
 * intended for use in the design, construction, operation or 
 * maintenance of any nuclear facility. 
 */

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.net.*;
import java.util.*;

// Listen on a port for connections and write back the current time.
public class NBTimeServer {
    private static final int DEFAULT_TIME_PORT = 8900;

    // Constructor with no arguments creates a time server on default port.
    public NBTimeServer(); throws Exception {
	acceptConnections(this.DEFAULT_TIME_PORT);;
    }

    // Constructor with port argument creates a time server on specified port.
    public NBTimeServer(int port); throws Exception {
	acceptConnections(port);;
    }

    // Accept connections for current time. Lazy Exception thrown.
    private static void acceptConnections(int port); throws Exception {
	// Selector for incoming time requests
	Selector acceptSelector = SelectorProvider.provider();.openSelector();;

	// Create a new server socket and set to non blocking mode
	ServerSocketChannel ssc = ServerSocketChannel.open();;
	ssc.configureBlocking(false);;

	// Bind the server socket to the local host and port

	InetAddress lh = InetAddress.getLocalHost();;
	InetSocketAddress isa = new InetSocketAddress(lh, port);;
	ssc.socket();.bind(isa);;
	
	// Register accepts on the server socket with the selector. This
	// step tells the selector that the socket wants to be put on the
	// ready list when accept operations occur, so allowing multiplexed
	// non-blocking I/O to take place.
	SelectionKey acceptKey = ssc.register(acceptSelector, 
					      SelectionKey.OP_ACCEPT);;
	
	int keysAdded = 0;
	
	// Here's where everything happens. The select method will
	// return when any operations registered above have occurred, the
	// thread has been interrupted, etc.
	while ((keysAdded = acceptSelector.select();); > 0); {
	    // Someone is ready for I/O, get the ready keys
	    Set readyKeys = acceptSelector.selectedKeys();;
	    Iterator i = readyKeys.iterator();;

	    // Walk through the ready keys collection and process date requests.
	    while (i.hasNext();); {
		SelectionKey sk = (SelectionKey);i.next();;
		i.remove();;
		// The key indexes into the selector so you
		// can retrieve the socket that's ready for I/O
		ServerSocketChannel nextReady = 
		    (ServerSocketChannel);sk.channel();;
		// Accept the date request and send back the date string
		Socket s = nextReady.accept();.socket();;
		// Write the current time to the socket
                PrintWriter out = new PrintWriter(s.getOutputStream();, true);;
		Date now = new Date();;
		out.println(now);;
		out.close();;
	    }
	}
    }

    // Entry point.
    public static void main(String[] args); {
	// Parse command line arguments and
	// create a new time server (no arguments yet);
	try {
		NBTimeServer nbt = new NBTimeServer();;
	} catch(Exception e); {
		e.printStackTrace();;		
	}
    }
}

分享到:
评论
1 楼 zzknight 2010-02-08  
代码中出现;; 这样的是有特殊意义的吗?

相关推荐

    xnio-nio-3.8.0.Final-API文档-中文版.zip

    赠送jar包:xnio-nio-3.8.0.Final.jar; 赠送原API文档:xnio-nio-3.8.0.Final-javadoc.jar; 赠送源代码:xnio-nio-3.8.0.Final-sources.jar; 赠送Maven依赖信息文件:xnio-nio-3.8.0.Final.pom; 包含翻译后的API...

    JAVA NIO 按行读取大文件,支持 GB级别

    设计思想: 每次通过nio读取字节到 fbb中 然后对fbb自己中的内容进行行判断即 10 回车 13 行号 0 文件结束 这样字节的判断,然后 返回行 如果 到达 fbb的结尾 还没有结束,就再通过nio读取一段字节,继续处理...

    httpcore-nio-4.4.6-API文档-中文版.zip

    赠送jar包:httpcore-nio-4.4.6.jar 赠送原API文档:httpcore-nio-4.4.6-javadoc.jar 赠送源代码:httpcore-nio-4.4.6-sources.jar 包含翻译后的API文档:httpcore-nio-4.4.6-javadoc-API文档-中文(简体)版.zip ...

    Java NIO 中文 Java NIO 中文 Java NIO 中文文档

    Java NIO 深入探讨了 1.4 版的 I/O 新特性,并告诉您如何使用这些特性来极大地提升您所写的 Java 代码的执行效率。这本小册子就程序员所面临的有代表性的 I/O 问题作了详尽阐述,并讲解了 如何才能充分利用新的 I/O ...

    JavaNIO chm帮助文档

    Java NIO系列教程(一) Java NIO 概述 Java NIO系列教程(二) Channel Java NIO系列教程(三) Buffer Java NIO系列教程(四) Scatter/Gather Java NIO系列教程(五) 通道之间的数据传输 Java NIO系列教程(六)...

    java nio中文版

    java NIO是 java New IO 的简称,在 jdk1.4 里提供的新 api 。 Sun 官方标榜的特性如下: – 为所有的原始类型提供 (Buffer) 缓存支持。 – 字符集编码解码解决方案。 – Channel :一个新的原始 I/O 抽象。 – 支持...

    Java IO, NIO and NIO.2 原版pdf by Friesen

    New I/O (NIO), and NIO.2 categories. You learn what each category offers in terms of its capabilities, and you also learn about concepts such as paths and Direct Memory Access. Chapters 2 through 5 ...

    JAVA NIO 按行读取大文件支持 GB级别-修正版

    设计思想: 每次通过nio读取字节到 fbb中 然后对fbb自己中的内容进行行判断即 10 回车 13 行号 0 文件结束 这样字节的判断,然后 返回行 如果 到达 fbb的结尾 还没有结束,就再通过nio读取一段字节,继续处理。 ...

    java NIO和java并发编程的书籍

    java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java NIO和java并发编程的书籍java...

    java nio 包读取超大数据文件

    Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据...

    Java IO, NIO and NIO.2(Apress,2015)

    Java I/O, NIO, and NIO.2 is a power-packed book that accelerates your mastery of Java's various I/O APIs. In this book, you'll learn about classic I/O APIs (File, RandomAccessFile, the stream classes ...

    java基于NIO实现Reactor模型源码.zip

    java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现Reactor模型源码java基于NIO实现...

    java NIO 视频教程

    Java NIO(New IO)是一个可以替代标准Java IO API的IO API(从Java 1.4开始),Java NIO提供了与标准IO不同的IO工作方式。 Java NIO: Channels and Buffers(通道和缓冲区) 标准的IO基于字节流和字符流进行操作的,...

    新输入输出NIO

    JDK 1.4 中引入的新输入输出 (NIO) 库在标准 Java 代码中提供了高速的、面向块的 I/O。本实用教程从高级概念到底层的编程细节,非常详细地介绍了 NIO 库。您将学到诸如缓冲区和通道这样的关键 I/O 元素的知识,并...

    nio入门 IBM教材,pdf格式

    新的输入/输出 (NIO) 库是在 JDK 1.4 中引入的。NIO 弥补了原来的 I/O 的不足,它在标准 Java 代码中提供了高速的、面向块的 I/O。通过定义包含数据的类,以及通过以块的形式处理这些数据,NIO 不用使用本机代码就...

    Java NIO英文高清原版

    Java NIO英文高清原版

    尚硅谷Java视频_NIO 视频教程

    尚硅谷_NIO_NIO 与 IO 区别 ·02. 尚硅谷_NIO_缓冲区(Buffer)的数据存取 ·03. 尚硅谷_NIO_直接缓冲区与非直接缓冲区 ·04. 尚硅谷_NIO_通道(Channel)的原理与获取 ·05. 尚硅谷_NIO_通道的数据传输与内存映射文件 ...

    httpcore-nio-4.4.15-API文档-中文版.zip

    赠送jar包:httpcore-nio-4.4.15.jar 赠送原API文档:httpcore-nio-4.4.15-javadoc.jar 赠送源代码:httpcore-nio-4.4.15-sources.jar 包含翻译后的API文档:httpcore-nio-4.4.15-javadoc-API文档-中文(简体)版....

    xnio-nio-3.8.4.Final-API文档-中文版.zip

    赠送jar包:xnio-nio-3.8.4.Final.jar; 赠送原API文档:xnio-nio-3.8.4.Final-javadoc.jar; 赠送源代码:xnio-nio-3.8.4.Final-sources.jar; 赠送Maven依赖信息文件:xnio-nio-3.8.4.Final.pom; 包含翻译后的API...

    httpcore-nio-4.4.5-API文档-中文版.zip

    赠送jar包:httpcore-nio-4.4.5.jar; 赠送原API文档:httpcore-nio-4.4.5-javadoc.jar; 赠送源代码:httpcore-nio-4.4.5-sources.jar; 赠送Maven依赖信息文件:httpcore-nio-4.4.5.pom; 包含翻译后的API文档:...

Global site tag (gtag.js) - Google Analytics