NIO

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()));
					//在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。  
					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).trim();
					System.out.println("客户端收到信息:" + msg);
					
					ByteBuffer outBuffer = ByteBuffer.wrap("来自客户端的消息".getBytes());
					channel.write(outBuffer);
					
				} else if (key.isWritable()) {
					// a channel is ready for writing
				}
				keyIterator.remove();
			}
		}
	}

}

 

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 {

		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 {
		
		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()));
					//在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。 
					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).trim();
					System.out.println("服务端收到信息:" + msg);
					ByteBuffer outBuffer = ByteBuffer.wrap("服务器的反馈消息!".getBytes());
					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();
	}
}

 

 

你可能感兴趣的:(NIO)