Java NIO

4人阅读 评论(0) 收藏 举报
分类:
package com.xiuye.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;

public class NIOServer {

	private Selector selector;
	public void init() throws IOException{
		this.selector = Selector.open();
		ServerSocketChannel channel = ServerSocketChannel.open();
		channel.configureBlocking(false);
		ServerSocket ss = channel.socket();
		ss.bind(new InetSocketAddress(8080));
		//server 注册 event accept
		channel.register(selector, SelectionKey.OP_ACCEPT);
	}

	public void start() throws IOException{
		while(true){
			this.selector.select();//blocking 阻塞
			Iterator<SelectionKey> it = this.selector.selectedKeys().iterator();
			while(it.hasNext()){
				SelectionKey key = it.next();
				it.remove();//删除防止下次重复处理
				if(key.isAcceptable()){
					accept(key);
				}
				else if(key.isReadable()){
					read(key);
				}

			}
		}
	}

	private void read(SelectionKey key) throws IOException {
		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		channel.read(buffer);
		String request = new String(buffer.array()).trim();
		System.out.println("Client Request MSG: "+request);
		ByteBuffer outBuffer = ByteBuffer.wrap("Request had received!".getBytes());
		channel.write(outBuffer);
		//channel.close();
	}

	private void accept(SelectionKey key) throws IOException {
		ServerSocketChannel serverChnnel = (ServerSocketChannel) key.channel();
		SocketChannel socketChannel = serverChnnel.accept();
		socketChannel.configureBlocking(false);
		socketChannel.register(selector, SelectionKey.OP_READ);
	}


	public static void main(String[] args) throws IOException {

		/**
		 * Selector and channel are independent
		 * Selector registers all kinds of channels
		 * Selector Event is SelectionKey
		 * All in all,
		 * Selector selects Channel
		 * Channel manipulates Buffer
		 * Selector registers next Channel (maybe different from previous one)
		 */
		NIOServer server = new NIOServer();
		server.init();
		server.start();

	}

}

package com.xiuye.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOClient {

	private Selector selector;

	private BufferedReader clientInput = new BufferedReader(new InputStreamReader(System.in));

	public void init() throws IOException{
		this.selector = Selector.open();
		SocketChannel channel = SocketChannel.open();
		channel.configureBlocking(false);
		channel.connect(new InetSocketAddress("127.0.0.1", 8080));
		channel.register(selector, SelectionKey.OP_CONNECT);
	}

	public void start() throws IOException{
		while(true){
			this.selector.select();//blocking
			Iterator<SelectionKey> it = this.selector.selectedKeys().iterator();
			while(it.hasNext()){
				SelectionKey key = it.next();
				it.remove();//delete this key from "keys set" in case of repetition
				if(key.isConnectable()){
					connect(key);
				}
				else if(key.isReadable()){
					read(key);
				}
			}
		}
	}



	private void read(SelectionKey key) throws IOException {

		SocketChannel channel = (SocketChannel) key.channel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		channel.read(buffer);
		String response = new String(buffer.array()).trim();
		System.out.println("Server Replied MSG: "+response);
		String nextRequest = clientInput.readLine();
		ByteBuffer outBuffer = ByteBuffer.wrap(nextRequest.getBytes());
		channel.write(outBuffer);
//		channel.close();
	}

	private void connect(SelectionKey key) throws IOException {
		SocketChannel channel = (SocketChannel)key.channel();
		if(channel.isConnectionPending()){//is connecting ...?
			if(channel.finishConnect()){
				channel.configureBlocking(false);
				channel.register(selector, SelectionKey.OP_READ);
				String request = clientInput.readLine();
				channel.write(ByteBuffer.wrap(request.getBytes()));
			}
			else{
				key.cancel();
			}
		}
	}

	public static void main(String[] args) throws IOException {
		//channel operate buffer not byte[]
		//channel register into seletor
		//selectionkey deleted in hand
		NIOClient client = new NIOClient();
		client.init();
		client.start();
	}

}




查看评论

JavaNIO chm帮助文档

  • 2017年10月09日 17:20
  • 163KB
  • 下载

JAVA NIO 实现网络编程

  • 2011年09月27日 01:25
  • 188KB
  • 下载

java NIO和java并发编程的书籍

  • 2011年11月13日 22:58
  • 3.87MB
  • 下载

java NIO文档

  • 2017年12月20日 12:26
  • 1.81MB
  • 下载

java nio 包读取超大数据文件

  • 2010年12月19日 16:40
  • 26KB
  • 下载

Java NIO编写Socket服务器的一个例子

Java中编写Socket服务器,通常有一下几种模式: 1. 一个链接一个线程;优点:程序编写简单; 缺点:如果链接非常多,分批的线程会非常多,机器可能资源耗尽而崩溃。 2.把每一个新链接,交接给一个...
  • xidianliuy
  • xidianliuy
  • 2016-06-08 14:02:18
  • 5082

说说java NIO的一些个人总结

首先了解下所谓的java nio是个什么东西! IO是靠字符或字节进行传输,比较慢! 而NIO是靠块, 也就相当于一个Buffer, 一块一块 的传输, 速度较快 ! 同时加入了多线程 的控制...
  • Truong
  • Truong
  • 2017-07-02 21:23:10
  • 5617

java nio原理和它的优点

要想讲清楚nio的原理和它的优点得先清楚Java应用程序的文件读写原理和虚拟内存的原理。Java文件读取原理可参见如下图: 当应用程序需要读取文件的时候,内核首先通过DMA技术将文件内容从磁...
  • u012684933
  • u012684933
  • 2015-11-06 15:20:14
  • 8150

Java NIO 详解(一)

NIO即新的输入输出,这个库是在JDK1.4中才引入的。它在标准java代码中提供了高速的面向块的IO操作。 一、基本概念描述1.1 I/O简介I/O即输入输出,是计算机与外界世界的一个借口。IO操作...
  • suifeng3051
  • suifeng3051
  • 2015-09-14 11:07:29
  • 24296

Java NIO系列教程(一) Java NIO 概述

  • 2016年11月28日 22:01
  • 262KB
  • 下载
    个人资料
    持之以恒
    等级:
    访问量: 23万+
    积分: 6097
    排名: 5131
    最新评论