`
dodoflying
  • 浏览: 180715 次
社区版块
存档分类
最新评论
阅读更多
今天研究了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  
代码中出现;; 这样的是有特殊意义的吗?

相关推荐

    Java NIO英文高清原版

    Java NIO,全称为Non-Blocking Input/Output(非阻塞输入/输出),是Java平台中用于替代标准I/O(BIO)模型的一种新机制。NIO在Java 1.4版本引入,提供了更高效的数据处理和通道通信方式,特别适用于高并发、大数据...

    java nio 包读取超大数据文件

    ### Java NIO 处理超大数据文件的知识点详解 #### 一、Java NIO简介 Java NIO(New IO)是Java平台上的新输入/输出流API,它提供了与传统IO(即Java IO)不同的数据处理方式。NIO在Java 1.4版本引入,并在后续版本...

    java NIO.zip

    Java NIO,全称为Non-Blocking Input/Output(非阻塞输入/输出),是Java标准库提供的一种替代传统的I/O模型的新技术。自Java 1.4版本引入NIO后,它为Java开发者提供了更高效的数据传输方式,尤其是在处理大量并发...

    基于nio实现的多文件上传源码

    在Java编程领域,NIO(New IO)是一个重要的特性,它是Java 1.4版本引入的,用于替代标准的IO API。NIO提供了一种非阻塞I/O操作的方式,特别适用于处理大量的并发连接,例如在文件传输、网络通信等场景。本主题...

    基于nio的简易聊天室

    在Java编程领域,NIO(New Input/Output)是一个重要的概念,它提供了非阻塞I/O操作的能力,相比传统的BIO(Blocking I/O),在处理大量并发连接时表现出更高的效率和性能。本项目"基于nio的简易聊天室"旨在通过NIO...

    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...

    httpcore-nio-4.3.jar包

    它基于Java NIO API,利用其非阻塞I/O特性,可以同时处理大量连接,尤其适合于高并发的网络环境。HttpCore NIO 4.3版是对该框架的进一步优化和完善,增强了对HTTP/1.1协议的支持,同时保持了良好的兼容性和稳定性。 ...

    《NIO与Socket编程技术指南》_高洪岩

    《NIO与Socket编程技术指南》是一本深入探讨Java NIO(New Input/Output)和Socket编程的专业书籍,由高洪岩撰写。本书主要针对Java开发者,旨在帮助他们理解和掌握这两种在开发网络应用中至关重要的技术。 Java ...

    java NIO详细教程

    ### Java NIO 详细教程知识点解析 #### 一、Java NIO 概述 Java NIO(New IO)是Java平台提供的一种新的IO操作模式,它首次出现在Java 1.4版本中,并在后续版本中不断完善。Java NIO 的设计目的是为了克服传统Java ...

    NIO 入门.chm,NIO 入门.chm

    **NIO(New Input/Output)是Java编程语言中用于替代标准I/O(BIO,Blocking I/O)的一组API,它提供了非阻塞式的I/O操作方式,极大地提升了Java在处理I/O密集型应用时的性能。NIO在Java 1.4版本中被引入,之后在...

    基于Spring Boot + NIO实现的电商平台见证宝服务

    本项目"基于Spring Boot + NIO实现的电商平台见证宝服务"旨在利用Spring Boot的便捷性与NIO(非阻塞I/O)的效率,来打造一个高效、稳定且可扩展的服务。下面将详细阐述其中涉及的关键技术点。 首先,Spring Boot是...

    基于java的BIO、NIO、AIO通讯模型代码实现

    Java作为一门广泛使用的开发语言,提供了多种I/O(Input/Output)通信模型,包括传统的阻塞I/O(BIO)、非阻塞I/O(NIO)以及异步I/O(AIO)。这些通信模型在不同的场景下有着各自的优势,理解和掌握它们对于优化...

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

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

    javaNiO.doc

    ### Java NIO (New IO) 详解 #### 1. 引言 在Java的世界里,I/O(Input/Output)操作是程序与外部环境进行交互的重要方式之一。随着技术的发展,传统I/O模型逐渐显露出一些局限性,特别是在处理高并发场景下,其...

    JAVA-NIO-DEMO

    Java NIO(New IO)是Java 1.4版本引入的一个新模块,它提供了一种不同于传统IO(基于字节流和字符流)的I/O操作方式。传统的IO模型是阻塞式的,而NIO的核心特点是非阻塞,这使得在处理大量并发I/O请求时更为高效。...

    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(Non-blocking Input/Output)是一种在Java中处理I/O操作的新方式,相比于传统的BIO(Blocking I/O),NIO提供了更高效的数据传输能力,尤其适合于高并发、低延迟的网络应用,如聊天服务器。在这个场景下,...

Global site tag (gtag.js) - Google Analytics