JAVA NIO

8 篇文章 0 订阅
5 篇文章 0 订阅

1.   基本 概念

IO 是主存和外部设备 ( 硬盘、终端和网络等 ) 拷贝数据的过程。 IO 是操作系统的底层功能实现,底层通过 I/O 指令进行完成。

所有语言运行时系统提供执行 I/O 较高级别的工具。 (c 的 printf scanf,java 的面向对象封装 )

2.    Java 标准 io 回顾

Java 标准 IO 类库是 io 面向对象的一种抽象。基于本地方法的底层实现,我们无须关注底层实现。 InputStream\OutputStream( 字节流 ) :一次传送一个字节。 Reader\Writer( 字符流 ) :一次一个字符。

3.    nio 简介

nio 是 java New IO 的简称,在 jdk1.4 里提供的新 api 。 Sun 官方标榜的特性如下:

–     为所有的原始类型提供 (Buffer) 缓存支持。

–     字符集编码解码解决方案。

–     Channel :一个新的原始 I/O 抽象。

–     支持锁和内存映射文件的文件访问接口。

–     提供多路 (non-bloking) 非阻塞式的高伸缩性网络 I/O 。

本文将围绕这几个特性进行学习和介绍。

4.   Buffer&Chanel

Channel 和 buffer 是 NIO 是两个最基本的数据类型抽象。

Buffer:

–        是一块连续的内存块。

–        是 NIO 数据读或写的中转地。

Channel:

–        数据的源头或者数据的目的地

–        用于向 buffer 提供数据或者读取 buffer 数据 ,buffer 对象的唯一接口。

–         异步 I/O 支持


                       图1:channel和buffer的关系


例子 1:CopyFile.java

package com.tb.nio.file;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class CopyFile {
	public static void main(String[] args) throws Exception {
		String infile = "C:\\copy.sql";
		String outfile = "C:\\copy.txt";
		// 获取源文件和目标文件的输入输出流
		FileInputStream fin = new FileInputStream(infile);
		FileOutputStream fout = new FileOutputStream(outfile);
		// 获取输入输出通道
		FileChannel fcin = fin.getChannel();
		FileChannel fcout = fout.getChannel();
		// 创建缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while (true) {
			// clear方法重设缓冲区,使它可以接受读入的数据
			buffer.clear();
			// 从输入通道中将数据读到缓冲区
			int r = fcin.read(buffer);
			// read方法返回读取的字节数,可能为零,如果该通道已到达流的末尾,则返回-1
			if (r == -1) {
				break;
			}
			// flip方法让缓冲区可以将新读入的数据写入另一个通道
			buffer.flip();
			// 从输出通道中将数据写入缓冲区
			fcout.write(buffer);
		}
	}
}

其中 buffer 内部结构如下 ( 下图拷贝自资料 ):


                                                 图2:buffer内部结构

一个 buffer 主要由 position,limit,capacity 三个变量来控制读写的过程。此三个变量的含义见如下表格:

参数

写模式    

读模式

position

当前写入的单位数据位置。

当前读取的单位数据位置。

limit

代表最多能写多少单位数据和容量是一样的。

代表最多能读多少单位数据,和之前写入的单位数据量一致。

capacity

buffer 容量

buffer 容量

Buffer 常见方法:

flip(): 写模式转换成读模式

rewind() :将 position 重置为 0 ,一般用于重复读。

clear() :清空 buffer ,准备再次被写入 (position 变成 0 , limit 变成 capacity) 。

compact(): 将未读取的数据拷贝到 buffer 的头部位。

mark() 、 reset():mark 可以标记一个位置, reset 可以重置到该位置。

Buffer 常见类型: ByteBuffer 、 MappedByteBuffer 、 CharBuffer 、 DoubleBuffer 、 FloatBuffer 、 IntBuffer 、 LongBuffer 、 ShortBuffer 。

channel 常见类型 :FileChannel 、 DatagramChannel(UDP) 、 SocketChannel(TCP) 、 ServerSocketChannel(TCP)

在本机上面做了个简单的性能测试。我的笔记本性能一般。 ( 具体代码可以见附件。见 nio.sample.filecopy 包下面的例子 ) 以下是参考数据:

      场景 1 : Copy 一个 370M 的文件

      场景 2: 三个线程同时拷贝,每个线程拷贝一个 370M 文件

package nio.sample.filecopy;

public class CommonCopy implements Runnable {

    String         fromFile;
    String         toFile;
    public boolean flag = false;

    public CommonCopy(String fromFile, String toFile){
        this.fromFile = fromFile;
        this.toFile = toFile;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }

}

package nio.sample.filecopy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class StreamFileCopy extends CommonCopy {

    public StreamFileCopy(String fromFile, String toFile){
        super(fromFile, toFile);
    }

    @Override
    public void run() {
        try {

            File fileIn = new File(fromFile);
            File fileOut = new File(toFile);
            FileInputStream fin = new FileInputStream(fileIn);
            FileOutputStream fout = new FileOutputStream(fileOut);
            byte[] buffer = new byte[8192];
            while (fin.read(buffer) != -1) {
                fout.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        flag = true;

    }

}

package nio.sample.filecopy;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 类StreamFileCopy.java的实现描述:通过FileInputStream来读写
 * 
 * @author yblin 2010-10-17 下午01:59:05
 */
public class StreamFileCopyWithBuffer extends CommonCopy {

    public StreamFileCopyWithBuffer(String fromFile, String toFile){
        super(fromFile, toFile);
    }

    @Override
    public void run() {
        try {

            File fileIn = new File(fromFile);
            File fileOut = new File(toFile);
            FileInputStream fin = new FileInputStream(fileIn);
            BufferedInputStream bin = new BufferedInputStream(fin);
            FileOutputStream fout = new FileOutputStream(fileOut);
            byte[] buffer = new byte[8192];
            while (bin.read(buffer) != -1) {
                fout.write(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        flag = true;

    }


}

package nio.sample.filecopy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 类NIOFileCopy.java的实现描述:使用NIO进行文件读写
 * 
 * @author yblin 2010-10-17 下午02:09:31
 */
public class NIOFileCopy extends CommonCopy {

    public NIOFileCopy(String fromFile, String toFile){
        super(fromFile, toFile);
    }

    @Override
    public void run() {
        try {

            File fileIn = new File(fromFile);
            File fileOut = new File(toFile);
            FileInputStream fin = new FileInputStream(fileIn);
            FileOutputStream fout = new FileOutputStream(fileOut);

            FileChannel fcIn = fin.getChannel();
            ByteBuffer bf = ByteBuffer.allocate(8192);
            FileChannel fcOut = fout.getChannel();
            while (fcIn.read(bf) != -1) {
                bf.flip();
                fcOut.write(bf);
                bf.clear();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        flag = true;

    }


}

package nio.sample.filecopy;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MappedFileCopy extends CommonCopy {

    public MappedFileCopy(String fromFile, String toFile){
        super(fromFile, toFile);
    }

    @Override
    public void run() {
        try {

            File fileIn = new File(fromFile);
            File fileOut = new File(toFile);

            RandomAccessFile raf = new RandomAccessFile(fileIn, "rw");
            // FileInputStream fin = new FileInputStream(fileIn);
            FileOutputStream fout = new FileOutputStream(fileOut);

            FileChannel fcIn = raf.getChannel();
            FileChannel fcOut = fout.getChannel();

            MappedByteBuffer mbb = fcIn.map(FileChannel.MapMode.READ_WRITE, 0, 8192);

            while (fcIn.read(mbb) != -1) {
                mbb.flip();
                fcOut.write(mbb);
                mbb.clear();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        flag = true;

    }

}
测试程序:
package nio.sample.filecopy;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestCopy {

    public static void main(String[] args) throws IOException, InterruptedException {
        File f = new File(TestCopy.class.getClassLoader().getSystemResource("fileConfig.properties").getFile());
        FileInputStream fIn = new FileInputStream(f);
        byte[] buffer = new byte[8192];
        fIn.read(buffer);

        String s = new String(buffer);

        String items[] = s.trim().split("\n");
        List<CommonCopy> fileCopys = new ArrayList<CommonCopy>();
        long start = System.currentTimeMillis();
        for (String item : items) {
            String fromTo[] = item.split(",");
//             CommonCopy fileCopy = new StreamFileCopy(fromTo[0].trim(), fromTo[1].trim());//time used46563
             CommonCopy fileCopy = new StreamFileCopyWithBuffer(fromTo[0].trim(), fromTo[1].trim());// time used54447
//            CommonCopy fileCopy = new NIOFileCopy(fromTo[0].trim(), fromTo[1].trim());
//             CommonCopy fileCopy = new MappedFileCopy(fromTo[0].trim(), fromTo[1].trim());

            fileCopys.add(fileCopy);
            Thread copy1 = new Thread(fileCopy);
            copy1.start();
            System.out.println(item);
        }

        while (true) {
            if (fileCopys.isEmpty()) {
                break;
            }
            Iterator<CommonCopy> it = fileCopys.iterator();
            while (it.hasNext()) {
                if (it.next().flag) {
                    it.remove();
                }
            }
            Thread.sleep(500);
        }
        long end = System.currentTimeMillis();
        System.out.println("time used" + (end - start));

    }
}

测试结果:

场景

FileInputStream+

FileOutputStream

FileInputStream+

BufferedInputStream+

FileOutputStream

ByteBuffer+

FileChannel

MappedByteBuffer

+FileChannel

场景一时间 ( 毫秒 )                 

25155

17500

19000

16500

场景二时间 ( 毫秒 )

69000

67031

74031

71016 


5.    nio.charset

字符编码解码 : 字节码本身只是一些数字,放到正确的上下文中被正确被解析。向 ByteBuffer 中存放数据时需要考虑字符集的编码方式,读取展示 ByteBuffer 数据时涉及对字符集解码。

Java.nio.charset 提供了编码解码一套解决方案。

以我们最常见的 http 请求为例,在请求的时候必须对请求进行正确的编码。在得到响应时必须对响应进行正确的解码。

以下代码向 baidu 发一次请求,并获取结果进行显示。例子演示到了 charset 的使用。

例子 2BaiduReader.java

package nio.readpage;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.net.InetSocketAddress;
import java.io.IOException;

public class BaiduReader {

	private Charset charset = Charset.forName("GBK");// 创建GBK字符集
	private SocketChannel channel;

	public void readHTMLContent() {
		try {
			InetSocketAddress socketAddress = new InetSocketAddress(
					"www.baidu.com", 80);
			//step1:打开连接
			channel = SocketChannel.open(socketAddress);
			//step2:发送请求,使用GBK编码
			channel.write(charset.encode("GET " + "/ HTTP/1.1" + "\r\n\r\n"));
			//step3:读取数据
			ByteBuffer buffer = ByteBuffer.allocate(1024);// 创建1024字节的缓冲
			while (channel.read(buffer) != -1) {
				buffer.flip();// flip方法在读缓冲区字节操作之前调用。
				System.out.println(charset.decode(buffer));
				// 使用Charset.decode方法将字节转换为字符串
				buffer.clear();// 清空缓冲
			}
		} catch (IOException e) {
			System.err.println(e.toString());
		} finally {
			if (channel != null) {
				try {
					channel.close();
				} catch (IOException e) {
				}
			}
		}
	}


	public static void main(String[] args) {
		new BaiduReader().readHTMLContent();
	}
}

6.      非阻塞 IO

关于非阻塞 IO 将从何为阻塞、何为非阻塞、非阻塞原理和异步核心 API 几个方面来理解。

何为阻塞?

一个常见的网络 IO 通讯流程如下 :


图3:网络通讯基本过程


从该网络通讯过程来理解一下何为阻塞 :

在以上过程中若连接还没到来,那么 accept 会阻塞 , 程序运行到这里不得不挂起, CPU 转而执行其他线程。

在以上过程中若数据还没准备好, read 会一样也会阻塞。

阻塞式网络 IO 的特点:多线程处理多个连接。每个线程拥有自己的栈空间并且占用一些 CPU 时间。每个线程遇到外部为准备好的时候,都会阻塞掉。阻塞的结果就是会带来大量的进程上下文切换。且大部分进程上下文切换可能是无意义的。比如假设一个线程监听一个端口,一天只会有几次请求进来,但是该 cpu 不得不为该线程不断做上下文切换尝试,大部分的切换以阻塞告终。

 

何为非阻塞?

下面有个隐喻:

一辆从 A 开往 B 的公共汽车上,路上有很多点可能会有人下车。司机不知道哪些点会有哪些人会下车,对于需要下车的人,如何处理更好?

1. 司机过程中定时询问每个乘客是否到达目的地,若有人说到了,那么司机停车,乘客下车。 ( 类似阻塞式 )

2. 每个人告诉售票员自己的目的地,然后睡觉,司机只和售票员交互,到了某个点由售票员通知乘客下车。 ( 类似非阻塞 )

很显然,每个人要到达某个目的地可以认为是一个线程,司机可以认为是 CPU 。在阻塞式里面,每个线程需要不断的轮询,上下文切换,以达到找到目的地的结果。而在非阻塞方式里,每个乘客 ( 线程 ) 都在睡觉 ( 休眠 ) ,只在真正外部环境准备好了才唤醒,这样的唤醒肯定不会阻塞。

  非阻塞的原理

把整个过程切换成小的任务,通过任务间协作完成。

由一个专门的线程来处理所有的 IO 事件,并负责分发。

事件驱动机制:事件到的时候触发,而不是同步的去监视事件。

线程通讯:线程之间通过 wait,notify 等方式通讯。保证每次上下文切换都是有意义的。减少无谓的进程切换。

以下是异步 IO 的结构:


Reactor 就是上面隐喻的售票员角色。每个线程的处理流程大概都是读取数据、解码、计算处理、编码、发送响应。

异步 IO 核心 API

Selector

异步 IO 的核心类,它能检测一个或多个通道 (channel) 上的事件,并将事件分发出去。

使用一个 select 线程就能监听多个通道上的事件,并基于事件驱动触发相应的响应。而不需要为每个 channel 去分配一个线程。

SelectionKey

包含了事件的状态信息和时间对应的通道的绑定。

例子 1 单线程实现监听两个端口。 ( 见 nio.asyn 包下面的例子。 )

package nio.asyn;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class OperationClient {

    // Charset and decoder for US-ASCII
    //private static Charset charset = Charset.forName("US-ASCII");

    // 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, int port) throws IOException {
        byte inBuffer[] = new byte[100];
        InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port);
        SocketChannel sc = null;
        while (true) {
            try {
                System.in.read(inBuffer);
                sc = SocketChannel.open();
                sc.connect(isa);
                dbuf.clear();
                dbuf.put(inBuffer);
                dbuf.flip();
                sc.write(dbuf);
                dbuf.clear();

            } finally {
                // Make sure we close the channel (and hence the socket)
                if (sc != null) sc.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //query("localhost", 8090);//A+B
        query("localhost", 9090);//A*B
    }
}

package nio.asyn;

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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

public class OperationServer implements Runnable {

    private int                 port1            = 8090;
    private int                 port2            = 9090;
    private Selector            selector;
    private ServerSocketChannel serverChannel1;
    private ByteBuffer          readBuffer       = ByteBuffer.allocate(8192);
    private ServerSocketChannel serverChannel2;
    private SocketChannel       socketChannel1;
    private SocketChannel       socketChannel2;
    private AddProcessor    client1Processor = new AddProcessor();
    private MultiProcessor    client2Processor = new MultiProcessor();

    public OperationServer(){
        initSelector();
    }

    @Override
    public void run() {
        while (true) {
            try {
                this.selector.select();
                Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator();
                while (selectedKeys.hasNext()) {
                    SelectionKey key = selectedKeys.next();
                    selectedKeys.remove();

                    if (!key.isValid()) {
                        continue;
                    }

                    if (key.isAcceptable()) {
                        this.accept(key);
                    } else if (key.isReadable()) {
                        this.read(key);
                    } else if (key.isWritable()) {
                        this.write(key);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void accept(SelectionKey key) throws IOException {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        if (serverSocketChannel.equals(serverChannel1)) {
            socketChannel1 = serverSocketChannel.accept();
            socketChannel1.configureBlocking(false);
            socketChannel1.register(this.selector, SelectionKey.OP_READ);
        } else {
            socketChannel2 = serverSocketChannel.accept();
            socketChannel2.configureBlocking(false);
            socketChannel2.register(this.selector, SelectionKey.OP_READ);
        }

    }

    public void read(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();

        this.readBuffer.clear();

        // Attempt to read off the channel
        int numRead;
        try {
            numRead = socketChannel.read(this.readBuffer);
        } catch (IOException e) {
            // The remote forcibly closed the connection, cancel
            // the selection key and close the channel.
            key.cancel();
            socketChannel.close();
            return;
        }

        if (numRead == -1) {
            // Remote entity shut the socket down cleanly. Do the
            // same from our end and cancel the channel.
            key.channel().close();
            key.cancel();
            return;
        }
        String input = new String(readBuffer.array()).trim();
        if (socketChannel.equals(socketChannel1)) {
            client1Processor.process(input);
        } else {
            client2Processor.process(input);
        }
    }

    public void write(SelectionKey key) {

    }

    /**
     * 注册事件到selector;
     */
    public void initSelector() {
        try {
            selector = SelectorProvider.provider().openSelector();
            this.serverChannel1 = ServerSocketChannel.open();
            serverChannel1.configureBlocking(false);
            InetSocketAddress isa = new InetSocketAddress("localhost", this.port1);
            serverChannel1.socket().bind(isa);
            serverChannel1.register(selector, SelectionKey.OP_ACCEPT);

            this.serverChannel2 = ServerSocketChannel.open();
            serverChannel2.configureBlocking(false);
            InetSocketAddress isa2 = new InetSocketAddress("localhost", this.port2);
            serverChannel2.socket().bind(isa2);
            serverChannel2.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        OperationServer server = new OperationServer();
        Thread t = new Thread(server);
        t.start();
    }

}

package nio.asyn;

public class AddProcessor {

	public void process(String input) {
		if (input != null) {
			String[] elements = input.split(",");
			if (elements.length != 2) {
				System.out
						.println("sorry, input expression error! right format:A+B");
				return;
			}
			double A = Double.parseDouble(elements[0]);
			double B = Double.parseDouble(elements[1]);

			System.out.println(A+"+"+B+"="+(A+B));
		} else {
			System.out.println("no input");
		}

	}
}

package nio.asyn;

public class MultiProcessor {

	public void process(String input) {
		if (input != null) {
			String[] elements = input.split(",");
			if (elements.length != 2) {
				System.out
						.println("sorry, input expression error! right format:A*B");
				return;
			}
			double A = Double.parseDouble(elements[0]);
			double B = Double.parseDouble(elements[1]);

			System.out.println(A+"*"+B+"="+(A*B));
		} else {
			System.out.println("no input");
		}

	}
}

例子 2 NIO 线程协作实现资源合理利用。 (wait,notify) 。 ( 见 nio.asyn.multithread 下的例子 )

package nio.asyn.multithread;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class OperationClient {

    // Charset and decoder for US-ASCII
    //private static Charset        charset = Charset.forName("US-ASCII");

    // 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, int port) throws IOException {
        byte inBuffer[] = new byte[100];
        InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port);
        SocketChannel sc = null;
        while (true) {
            try {
                System.in.read(inBuffer);
                sc = SocketChannel.open();
                sc.connect(isa);
                dbuf.clear();
                dbuf.put(inBuffer);
                dbuf.flip();
                sc.write(dbuf);
                dbuf.clear();

            } finally {
                // Make sure we close the channel (and hence the socket)
                if (sc != null) sc.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        query("localhost", 8090);//A+B
//        query("localhost", 9090);//A*B
    }
}

package nio.asyn.multithread;

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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

public class SelectThread implements Runnable {

	private int port1 = 8090;
	private Selector selector;
	private ServerSocketChannel serverChannel1;
	private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
	private SocketChannel socketChannel1;
	private Worker worker;

	public SelectThread(Worker worker) {
		this.worker = worker;
		initSelector();
	}

	@Override
	public void run() {
		while (true) {
			try {
				this.selector.select();
				Iterator<SelectionKey> selectedKeys = this.selector.selectedKeys().iterator();
				while (selectedKeys.hasNext()) {
					SelectionKey key = selectedKeys.next();
					selectedKeys.remove();

					if (!key.isValid()) {
						continue;
					}

					if (key.isAcceptable()) {
						this.accept(key);
					} else if (key.isReadable()) {
						this.read(key);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void accept(SelectionKey key) throws IOException {
		ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key
				.channel();
		if (serverSocketChannel.equals(serverChannel1)) {
			socketChannel1 = serverSocketChannel.accept();
			socketChannel1.configureBlocking(false);
			socketChannel1.register(this.selector, SelectionKey.OP_READ);
		}

	}

	public void read(SelectionKey key) throws IOException {
		SocketChannel socketChannel = (SocketChannel) key.channel();

		this.readBuffer.clear();

		// Attempt to read off the channel
		int numRead;
		try {
			numRead = socketChannel.read(this.readBuffer);
		} catch (IOException e) {
			// The remote forcibly closed the connection, cancel
			// the selection key and close the channel.
			key.cancel();
			socketChannel.close();
			return;
		}

		if (numRead == -1) {
			// Remote entity shut the socket down cleanly. Do the
			// same from our end and cancel the channel.
			key.channel().close();
			key.cancel();
			return;
		}
		String input = new String(readBuffer.array()).trim();
		if (socketChannel.equals(socketChannel1)) {
			EventData eventData = new EventData(input);
			worker.processData(eventData);
		}
	}

	/**
	 * 注册事件到selector;
	 */
	public void initSelector() {
		try {
			selector = SelectorProvider.provider().openSelector();
			this.serverChannel1 = ServerSocketChannel.open();
			serverChannel1.configureBlocking(false);
			InetSocketAddress isa = new InetSocketAddress("localhost",
					this.port1);
			serverChannel1.socket().bind(isa);
			serverChannel1.register(selector, SelectionKey.OP_ACCEPT);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Worker worker = new Worker();// process incoming data.
		SelectThread select = new SelectThread(worker);
		Thread selectThread = new Thread(select);
		Thread workerThread = new Thread(worker);
		selectThread.start();
		workerThread.start();
	}
}

package nio.asyn.multithread;

import java.util.LinkedList;
import java.util.List;

public class Worker implements Runnable {

	private List<EventData> queue = new LinkedList<EventData>();

	public void processData(EventData event) {
		synchronized (queue) {
			queue.add(event);
			queue.notify();
		}
	}

	public void run() {
		EventData eventData;
		while (true) {
			// Wait for data to become available
			synchronized (queue) {
				while (queue.isEmpty()) {
					try {
						System.out
								.println("No data to process, worker thread will sleep.");
						queue.wait();
					} catch (InterruptedException e) {
					}
					eventData = (EventData) queue.remove(0);
					System.out.println("Client event is:"
							+ eventData.getMessage());
				}

			}
		}
	}
}

package nio.asyn.multithread;

public class EventData {
	String message;
	String fromIp;

	public EventData(String message) {
		this.message = message;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getFromIp() {
		return fromIp;
	}

	public void setFromIp(String fromIp) {
		this.fromIp = fromIp;
	}
}

本文所有的代码(还有没有贴出来的),一同在http://download.csdn.net/detail/geli_hero/4289346,供大家分享!

(注:本文是转载文章,源码部分是原作者首创)







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值