首页 > 其他分享 >NIO

NIO

时间:2023-05-29 12:35:24浏览次数:48  
标签:key java NIO selector ByteBuffer import channel


package com.jaeson.javastudy;

import java.util.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;


public class NIOTest {
	
	public static void fileChannelRead() throws Exception {

		@SuppressWarnings("all")
		RandomAccessFile raf = new RandomAccessFile("C:\\hello\\hello.txt", "rw");

		//FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下。
		FileChannel inChannel = raf.getChannel();
		
		ByteBuffer buff = ByteBuffer.allocate(16);
		int bytesRead;
		//读取数据到Buffer
		while ((bytesRead = inChannel.read(buff)) != -1) {
			
			System.out.println("Read " + bytesRead);
			
			//反转Buffer, 将Buffer从写模式切换到读模式
			buff.flip();
			
			byte[] result = new byte[16];
			int i = 0;
			while(buff.hasRemaining()) {
				result[i++] = buff.get();
			}
			System.out.println(new String(result));
			
			//clear()方法会清空整个缓冲区。compact()方法只会清除已经读过的数据。
			//任何未读的数据都被移到缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。 
			buff.clear();
		}
		
		inChannel.close();
	}

	public static void fileChannelWrite() throws Exception {
		
		@SuppressWarnings("all")
		FileOutputStream fos = new FileOutputStream(new File("C:\\hello\\hello_cp.txt"));
		//FileChannel无法设置为非阻塞模式,它总是运行在阻塞模式下。
		FileChannel outChannel = fos.getChannel();
		
		ByteBuffer buff = ByteBuffer.allocate(1024);
		buff.clear();
		
		buff.put("你好中国!hello world!".getBytes());
		
		buff.flip();
		
		//因为无法保证write()方法一次能向FileChannel写入多少字节,因此需要重复调用write()方法,
		//直到Buffer中已经没有尚未写入通道的字节。 
		while(buff.hasRemaining()) {
			outChannel.write(buff);
		}
		
		outChannel.close();
	}
	
	public static void selector() throws Exception {
		
		ServerSocketChannel serverChannel = ServerSocketChannel.open();
		//置通道为非阻塞 
		serverChannel.configureBlocking(false);
		serverChannel.socket().bind(new InetSocketAddress(8080));
		//获得一个通道管理器 
		Selector selector = Selector.open();
		
		//将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,  
		//当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。  
		serverChannel.register(selector, SelectionKey.OP_ACCEPT);
		// 轮询访问selector  
		while (true) {
			//当注册的事件到达时,方法返回;否则,该方法会一直阻塞  
			selector.select();
			// 获得selector中选中的项的迭代器,选中的项为注册的事件 
			Iterator<SelectionKey> it = selector.selectedKeys().iterator();  
			while (it.hasNext()) {
				
				SelectionKey key = (SelectionKey) it.next();
				
				if(key.isAcceptable()) {
					// a connection was accepted by a ServerSocketChannel.
					ServerSocketChannel server = (ServerSocketChannel) key.channel();
					// 获得和客户端连接的通道 
					SocketChannel channel = server.accept();
					// 设置成非阻塞 
					channel.configureBlocking(false);

					//在这里可以给客户端发送信息哦
					channel.write(ByteBuffer.wrap(new String("你好,来自服务器端的问候!").getBytes("utf-8")));
					//在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。 
					channel.register(selector, SelectionKey.OP_READ);

				} else if (key.isConnectable()) {
					// a connection was established with a remote server.
				} else if (key.isReadable()) {
					// a channel is ready for reading
					// 服务器可读取消息:得到事件发生的Socket通道  
					SocketChannel channel = (SocketChannel) key.channel();
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					channel.read(buffer);
					byte[] data = buffer.array();
					String msg = new String(data, "utf-8").trim();
					System.out.println("服务端收到信息:" + msg);
					ByteBuffer outBuffer = ByteBuffer.wrap(("服务器的反馈消息!" + System.currentTimeMillis()).getBytes("utf-8"));
					channel.write(outBuffer);
					
				} else if (key.isWritable()) {
					// a channel is ready for writing
				}
				
				// 删除已选的key,以防重复处理  
				it.remove();
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		//fileChannelRead();
		//fileChannelWrite();
		selector();
	}
}

 

 

package com.jaeson.javastudy;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.channels.Selector;
import java.nio.channels.SelectionKey;
import java.util.Iterator;
import java.util.Set;

public class NIOSocketTest {

	public static void main(String[] args) throws Exception {
		
		SocketChannel socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		Selector selector = Selector.open();
		socketChannel.connect(new InetSocketAddress("localhost", 8080));
		socketChannel.register(selector, SelectionKey.OP_CONNECT);
		
		while(true) {
			
			selector.select();
			
			Set<SelectionKey> selectedKeys = selector.selectedKeys();
			Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
			while(keyIterator.hasNext()) {
				
				SelectionKey key = keyIterator.next();
				if(key.isAcceptable()) {
					// a connection was accepted by a ServerSocketChannel.
				} else if (key.isConnectable()) {
					// a connection was established with a remote server.
					SocketChannel channel = (SocketChannel) key.channel();
					// 如果正在连接,则完成连接  
					if(channel.isConnectionPending()) {
						channel.finishConnect();
					}  
					// 设置成非阻塞  
					channel.configureBlocking(false);
					
					//在这里可以给服务端发送信息
					channel.write(ByteBuffer.wrap(new String("你好,来自客户端的问候").getBytes("utf-8")));
					//在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。  
					channel.register(selector, SelectionKey.OP_READ);

				} else if (key.isReadable()) {
					// a channel is ready for reading
					// 服务器可读取消息:得到事件发生的Socket通道  
					SocketChannel channel = (SocketChannel) key.channel();
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					channel.read(buffer);
					byte[] data = buffer.array();
					String msg = new String(data, "utf-8").trim();
					System.out.println("客户端收到信息:" + msg);
					
					ByteBuffer outBuffer = ByteBuffer.wrap(("服务器的反馈消息!" + new java.util.Random().nextInt(100)).getBytes("utf-8"));
					channel.write(outBuffer);
					
				} else if (key.isWritable()) {
					// a channel is ready for writing
				}
				keyIterator.remove();
			}
		}
	}

}

 

标签:key,java,NIO,selector,ByteBuffer,import,channel
From: https://blog.51cto.com/u_16131764/6370070

相关文章

  • amzon s3/minio获取预签名上传url,及js使用预签名url上传文件
      $("#btnSubmit").click(function(event){varfile=$("#ipfile")[0].files[0];varcontentType=!!file.type?file.type:"video/x-flv";//请求api接口:调用amzons3/minio的sdk获取临时上传......
  • java中的BIO NIO AIO有什么区别?
    BIO、NIO和AIO都是Java中用于处理网络编程的技术,它们的主要区别如下:BIO:BIO(BlockingIO)阻塞式IO,指I/O的读写操作是阻塞的。当读写操作发生时,线程被阻塞,一直等到I/O完成才返回。BIO是Java最早的网络编程API,也是最常用的API。BIO的实现简单,易于理解和使用,但是由于阻塞......
  • 使用minio进行文件存储
    一.Docker拉取镜像(确保自己的服务器已经安装Docker)dockerpullminio/minio二.启动一个miniio容器dockerrun--nameminio-p9090:9000-p9999:9999-d\--restart=always-e\"MINIO_ROOT_USER=minio"\-e"MINIO_ROOT_PASSWORD=minio123"\-v/home/minio/......
  • MT8395处理器性能参数_Genio 1200芯片规格介绍资料
    联发科技(MediaTek)推出了他们的最新通用型AIoT芯片,MT8395(Genio1200)这款芯片专为高性能物联网应用和人工智能应用而设计,是一款集成了8核CPU和集成了五核图形处理器的高性能芯片。它是使用6纳米工艺制造而成的,内置了独立的双核AI处理器单元(APU),适用于用于智能家电、中控设备......
  • [ICDE 2023] Voting-based Opinion Maximization
    [ICDE2023]Voting-basedOpinionMaximizationApplication在总统大选时,会有许多候选者,这些候选者都希望能够被选上,他们可以通过寻找一组种子节点(即社交网络上的用户),靠他们的影响力(本文采用opinion,和influence不同),使得这个目标候选者在大选中可以获胜。除此之外。一般投票都会......
  • Java网络编程----通过实现简易聊天工具来聊聊NIO
    前文我们说过了BIO,今天我们聊聊NIO。NIO是什么?NIO官方解释它为NewlO,由于其特性我们也称之为,Non-BlockingIO。这是jdk1.4之后新增的一套IO标准。为什么要用NIO呢?我们再简单回顾下BIO:阻塞式IO,原理很简单,其实就是多个端点与服务端进行通信时,每个客户端有一个自己的socket,他们与服......
  • 数字型union注入
           ......
  • union注入
              ......
  • Spring boot 整合 ffmpeg 实现给视频添加文字水印 只有上传minio(理论通用!!)
    只要有ffmpeg命令理论可以实现所有ffmpeg能做的的事儿!!思路:前端上传视频通过commons-io的FileUtils.copyInputStreamToFile()将流复制到文件中java执行ffmpeg命令对这个文件进行转换输出到另外一个临时文件在将添加水印后的文件转成inputStream流上传到minio(本人小白可能有......
  • Linux安装MinIO
    第一步,进入/opt目录,创建minio文件夹cd/optmkdirminio 第二步,wget下载安装包:wgethttps://dl.minio.io/server/minio/release/linux-amd64/minio 第三步,进入minio文件夹创建log文件cd/miniotouchminio.log 第四步,赋予minio文件执行权限chmod777minio第五步,......