`
envy2002
  • 浏览: 151721 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

java nio测试

 
阅读更多

  import java.io.IOException;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
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.Iterator;
import java.util.Set;

public class NIOServer {
	
	/*标识数字*/
	private  int flag = 0;
	/*缓冲区大小*/
	private  int BLOCK = 4096;
	/*接受数据缓冲区*/
	private  ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);
	/*发送数据缓冲区*/
	private  ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);
	private  Selector selector;

	public NIOServer(int port) throws IOException {
		// 打开服务器套接字通道
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		// 服务器配置为非阻塞
		serverSocketChannel.configureBlocking(false);
		// 检索与此通道关联的服务器套接字
		ServerSocket serverSocket = serverSocketChannel.socket();
		// 进行服务的绑定
		serverSocket.bind(new InetSocketAddress(port));
		// 通过open()方法找到Selector
		selector = Selector.open();
		// 注册到selector,等待连接
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		System.out.println("Server Start----8888:");
	}


	// 监听
	private void listen() throws IOException {
		while (true) {
			// 选择一组键,并且相应的通道已经打开
			selector.select();
			// 返回此选择器的已选择键集。
			Set<SelectionKey> selectionKeys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = selectionKeys.iterator();
			while (iterator.hasNext()) {		
				SelectionKey selectionKey = iterator.next();
				iterator.remove();
				handleKey(selectionKey);
			}
		}
	}

	// 处理请求
	private void handleKey(SelectionKey selectionKey) throws IOException {
		// 接受请求
		ServerSocketChannel server = null;
		SocketChannel client = null;
		String receiveText;
		String sendText;
		int count=0;
		// 测试此键的通道是否已准备好接受新的套接字连接。
		if (selectionKey.isAcceptable()) {
			// 返回为之创建此键的通道。
			server = (ServerSocketChannel) selectionKey.channel();
			// 接受到此通道套接字的连接。
			// 此方法返回的套接字通道(如果有)将处于阻塞模式。
			client = server.accept();
			// 配置为非阻塞
			client.configureBlocking(false);
			// 注册到selector,等待连接
			client.register(selector, SelectionKey.OP_READ);
		} else if (selectionKey.isReadable()) {
			// 返回为之创建此键的通道。
			client = (SocketChannel) selectionKey.channel();
			//将缓冲区清空以备下次读取
			receivebuffer.clear();
			//读取服务器发送来的数据到缓冲区中
			count = client.read(receivebuffer);	
			if (count > 0) {
				receiveText = new String( receivebuffer.array(),0,count);
				System.out.println("服务器端接受客户端数据--:"+receiveText);
//				try {
//					Thread.sleep(3000);
//				} catch (InterruptedException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
				client.register(selector, SelectionKey.OP_WRITE);
			}
		} else if (selectionKey.isWritable()) {
			//将缓冲区清空以备下次写入
			sendbuffer.clear();
			// 返回为之创建此键的通道。
			client = (SocketChannel) selectionKey.channel();
			sendText="message from server--" + flag++;
			//向缓冲区中输入数据
			sendbuffer.put(sendText.getBytes());
			 //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位
			sendbuffer.flip();
			//输出到通道
			client.write(sendbuffer);
			System.out.println("服务器端向客户端发送数据--:"+sendText);
//			try {
//				Thread.sleep(3000);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			client.register(selector, SelectionKey.OP_READ);
		}
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		int port = 8888;
		NIOServer server = new NIOServer(port);
		server.listen();
	}
}

 

 

 

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.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOClient {

	/*标识数字*/
	private static int flag = 0;
	/*缓冲区大小*/
	private static int BLOCK = 4096;
	/*接受数据缓冲区*/
	private static ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);
	/*发送数据缓冲区*/
	private static ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);
	/*服务器端地址*/
	private final static InetSocketAddress SERVER_ADDRESS = new InetSocketAddress(
			"localhost", 8888);

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		// 打开socket通道
		SocketChannel socketChannel = SocketChannel.open();
		// 设置为非阻塞方式
		socketChannel.configureBlocking(false);
		// 打开选择器
		Selector selector = Selector.open();
		// 注册连接服务端socket动作
		socketChannel.register(selector, SelectionKey.OP_CONNECT);
		// 连接
		socketChannel.connect(SERVER_ADDRESS);
		// 分配缓冲区大小内存
		
		Set<SelectionKey> selectionKeys;
		Iterator<SelectionKey> iterator;
		SelectionKey selectionKey;
		SocketChannel client;
		String receiveText;
		String sendText;
		int count=0;

		while (true) {
			//选择一组键,其相应的通道已为 I/O 操作准备就绪。
			//此方法执行处于阻塞模式的选择操作。
			selector.select();
			//返回此选择器的已选择键集。
			selectionKeys = selector.selectedKeys();
			//System.out.println(selectionKeys.size());
			iterator = selectionKeys.iterator();
			while (iterator.hasNext()) {
				selectionKey = iterator.next();
				if (selectionKey.isConnectable()) {
					System.out.println("client connect");
					client = (SocketChannel) selectionKey.channel();
					// 判断此通道上是否正在进行连接操作。
					// 完成套接字通道的连接过程。
					if (client.isConnectionPending()) {
						client.finishConnect();
						System.out.println("完成连接!");
						sendbuffer.clear();
						sendbuffer.put("Hello,Server".getBytes());
						sendbuffer.flip();
						client.write(sendbuffer);
					}
					client.register(selector, SelectionKey.OP_READ);
				} else if (selectionKey.isReadable()) {
					client = (SocketChannel) selectionKey.channel();
					//将缓冲区清空以备下次读取
					receivebuffer.clear();
					//读取服务器发送来的数据到缓冲区中
					count=client.read(receivebuffer);
					if(count>0){
						receiveText = new String( receivebuffer.array(),0,count);
						System.out.println("客户端接受服务器端数据--:"+receiveText);
						try {
							Thread.sleep(3000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						client.register(selector, SelectionKey.OP_WRITE);
					}

				} else if (selectionKey.isWritable()) {
					sendbuffer.clear();
					client = (SocketChannel) selectionKey.channel();
					sendText = "message from client--11111111111111111" + (flag++);
					sendbuffer.put(sendText.getBytes());
					 //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位
					sendbuffer.flip();
					client.write(sendbuffer);
					System.out.println("客户端向服务器端发送数据--:"+sendText);
//					try {
//						Thread.sleep(3000);去不去掉是有区别的,去掉,输出111222
//					} catch (InterruptedException e) {//不去掉,输出111,222
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
					sendText = "message from client--22222222222222222222" + (flag++);
					sendbuffer.clear();
					sendbuffer.put(sendText.getBytes());
					sendbuffer.flip();
					client.write(sendbuffer);
					System.out.println("客户端向服务器端发送数据--:"+sendText);
					client.register(selector, SelectionKey.OP_READ);
				}
			}
			selectionKeys.clear();
		}
	}
}
分享到:
评论

相关推荐

    Java NIO测试示例

    Java NIO,全称为Non-Blocking Input/Output(非阻塞输入/输出),是Java从1.4版本开始引入的一种新的I/O模型,它为Java应用程序提供了更高效、灵活的I/O操作方式。NIO与传统的 Blocking I/O(阻塞I/O)模式相比,...

    java nio与io性能测试

    本文将深入探讨Java NIO与IO的性能测试,并通过代码实例来展示它们之间的差异。 首先,我们来看传统的Java IO模型。IO模型基于流,数据是从输入流到输出流的单向传输。例如,`FileInputStream`和`FileOutputStream`...

    java nio 聊天室源码

    Java NIO(New IO)是Java 1.4版本引入的一个新模块,全称为New Input/Output,是对传统IO API的扩展。它提供了一种更高效、更具选择性的IO操作方式,尤其适用于高并发和大数据处理场景。在这个“java nio 聊天室...

    Java NIO与IO性能对比分析.pdf

    在性能对比测试中,实验结果表明,基于NIO的新服务器模型在处理高并发时,平均响应时间仅为2.09毫秒,且CPU占用率保持在68.5%的较低水平。与之相比,传统IO服务器模型在处理并发流量时,不仅性能上无法达到新模型的...

    JAVA nio异步长连接服务端与客户端

    至于文件列表中的"SwitchyOmega_Chromium.crx",这看起来像是一个Chrome浏览器的扩展文件,与Java NIO并不直接相关,可能是用于辅助测试或监控网络通信的工具。而"channel"这个文件名没有具体扩展名,可能是代码、...

    java nio非阻塞编程-高级应用(端口代理)

    经过我2个月的深入学习,反复修改测试,开发出一个已经能稳定使用的端口代理程序,源代码没有应用所有nio知识,但比较全面的覆盖了nio编程中需要注意的几点,如果有什么问题,可以联系我:gypzfabc@126.com

    JAVA BIO AIO NIO测试代码

    对java io总结时编写的测试代码,包括BIO,NIO,AIO的实现,Java io操作是编程人员经常使用到的,以前只是使用没有对这三种IO做系统的了解,本文将对这三种IO作详细的介绍并附有测试完整代码

    Java IO NIO and NIO 2 无水印pdf

    Java IO NIO and NIO 2 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn...

    JAVA IO and NIO

    在IntelliJ IDEA中,开发者可以方便地使用Java IO和NIO编写和测试相关的代码。IDE提供了强大的代码补全、调试和测试工具,使得开发过程更加高效。对于Java IO,IntelliJ IDEA会自动处理流的关闭,对于NIO,它也提供...

    ServerBootstrap实现nio.rar_NIO_ServerBootstrap_heart8w9_java nio

    在Java网络编程中,`ServerBootstrap` 是一个用于构建高性能异步网络应用的工具,它主要用在NIO(Non-blocking I/O)模式下。NIO(非阻塞I/O)是Java提供的一种I/O模型,它允许一个线程处理多个输入/输出流,与传统...

    nio-benchmark:Java NIO回显服务器的基准测试

    使用JMH的Java NIO回显服务器的基准测试 基准测试针对各种服务器运行相同的客户端代码。 客户 客户端主程序是nio.JMHClientMain,具有可选参数: thread = 确定初始化的客户端数(默认为1) cycle = 如果为true,...

    java jre7里的nio实现稳健监控

    Java JRE7引入了NIO.2(New I/O 2)框架,显著改进了对文件系统操作的支持,其中最重要的增强之一就是引入了WatchService服务。这个服务允许程序以一种高效且优雅的方式监控文件或目录的变化,而无需像JRE6之前那样...

    基于java nio的远程调用框架.zip

    然而,NIO的编程模型相对复杂,需要更精确的控制并发状态,因此在实际应用中需要谨慎设计和测试。在Java 7及以后的版本中,还引入了NIO.2,提供了更高级别的文件系统访问接口,使得NIO更加易用和强大。

    基于Java NIO实现五子棋游戏.zip

    《基于Java NIO实现五子棋游戏》是一个适合学习与实践的Java开发项目,它将游戏编程与非阻塞I/O(NIO)技术相结合,为开发者提供了丰富的学习素材。以下将详细介绍该项目涉及的主要知识点: 1. **Java基础知识**:...

    使用Java NIO编写高性能的服务器.doc

    /** 测试文件下载的NIOServer */ public class NIOServer { static int BLOCK = 4096; // 每次发送的数据块大小 // 处理与客户端的交互 public class HandleClient implements Runnable { // ... } public ...

    默蓝网络通信测试工具(NIOSocket工具)支持TCP/IP和HTTP通信-网络通信开发人员必备

    《网络通信测试与Java NIO Socket编程详解》 在信息技术高速发展的今天,网络通信成为了软件开发中的重要一环。为了确保网络应用的稳定性和效率,网络通信测试工具扮演了不可或缺的角色。"默蓝网络通信测试工具(NIO...

    java_Nio_server_and_j2me_client.rar_J2ME SERVER_NIO_j2me_j2me ni

    描述中的"java nio 服务器范例及j2me代码连接服务器的测试代码"暗示了这个压缩包中包含了实现NIO服务器的Java代码和J2ME客户端的源代码,用于测试客户端如何与NIO服务器进行通信。这可能是通过创建一个简单的TCP连接...

    nio-samples:Java NIO库使用示例

    创建10000个客户端连接的类,您可以在nio服务器上测试负载。 监视服务API的简单用法。 监视预定义目录中的更改的类。 您可以播放生成的jar文件。 请按照以下步骤操作: 运行maven命令:“ mvn clean install”...

    多线程精品资源--Java NIO+多线程实现聊天室.zip

    在Java编程中,多线程和非阻塞I/O(NIO)是两个核心概念,它们在构建高性能、高并发的应用程序中起着至关重要的作用。在这个“多线程精品资源--Java NIO+多线程实现聊天室”的压缩包中,我们可以推测它包含了一套...

Global site tag (gtag.js) - Google Analytics