当前位置:首页 > 开发 > 编程语言 > Java IO > 正文

NIO示例

发表于: 2015-05-10   作者:daysinsun   来源:转载   浏览:
nio
摘要: NIO服务端代码: public class NIOServer { private Selector selector; public void startServer(int port) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(
NIO服务端代码:
public class NIOServer {
	
	private Selector selector;

	
	public void startServer(int port) throws IOException {

		ServerSocketChannel serverChannel = ServerSocketChannel.open();
		// 设置通道为非阻塞
		serverChannel.configureBlocking(false);

		serverChannel.socket().bind(new InetSocketAddress(port));

		this.selector = Selector.open();
		
		serverChannel.register(selector, SelectionKey.OP_ACCEPT);
	}

	
	public void listen() throws IOException {
		while (true) {
			//当注册的事件到达时,方法返回;否则,该方法会一直阻塞
			selector.select();
			Iterator<SelectionKey> it = this.selector.selectedKeys().iterator();
			while (it.hasNext()) {
				SelectionKey key = (SelectionKey) it.next();
				// 此处一定要删除
				it.remove();

				if (key.isAcceptable()) {
				    
					ServerSocketChannel server = (ServerSocketChannel) key
							.channel();
					
					SocketChannel channel = server.accept();
					System.out.println("remote socket is:"+channel.socket().getInetAddress());
					channel.configureBlocking(false);

					channel.write(ByteBuffer.wrap(new String("send one msg to client").getBytes()));
	
					channel.register(this.selector, SelectionKey.OP_READ);
					
				} else if (key.isReadable()) {
						read(key);
				}

			}

		}
	}
	
	public void read(SelectionKey key) throws IOException{
	
		SocketChannel channel = (SocketChannel) key.channel();
		
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		int len = channel.read(buffer);
		byte[] data = new byte[len];
		System.arraycopy(buffer.array(), 0, data, 0, len);
		String msg = new String(data).trim();
		System.out.println("server receive one msg:"+msg);
		ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
		channel.write(outBuffer);
	}
	
	public static void main(String[] args) throws IOException {
		NIOServer server = new NIOServer();
		server.startServer(8080);
		server.listen();
	}

}


NIO客户端代码:
public class NIOClient {
    
	private Selector selector;

	
	public void initClient(String ip,int port) throws IOException {
	
		SocketChannel channel = SocketChannel.open();
		
		channel.configureBlocking(false);
		
		this.selector = Selector.open();
		
		channel.connect(new InetSocketAddress(ip,port));
		channel.register(selector, SelectionKey.OP_CONNECT);
	}

	public void listen() throws IOException {
		while (true) {
			selector.select();
			Iterator<SelectionKey> it = this.selector.selectedKeys().iterator();
			while (it.hasNext()) {
				SelectionKey key = (SelectionKey) it.next();

				it.remove();

				if (key.isConnectable()) {
					SocketChannel channel = (SocketChannel) key.channel();
					if(channel.isConnectionPending()){
						channel.finishConnect();
						
					}

					channel.configureBlocking(false);

					channel.write(ByteBuffer.wrap(new String("你在他乡还好吗").getBytes()));

					channel.register(this.selector, SelectionKey.OP_READ);
					
				} else if (key.isReadable()) {
						read(key);
				}

			}

		}
	}

	public void read(SelectionKey key) throws IOException{
	    SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        int len = channel.read(buffer);
        byte[] data = new byte[len];
        System.arraycopy(buffer.array(), 0, data, 0, len);
        String msg = new String(data).trim();
        System.out.println("client receive one msg:"+msg);
        ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
	}
	
	
	public static void main(String[] args) throws IOException {
		NIOClient client = new NIOClient();
		client.initClient("localhost",8080);
		client.listen();
	}

}

NIO示例

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

我来说两句
评论内容:
验  证  码:
 
(网友评论仅供其表达个人看法,并不表明本站同意其观点或证实其描述。)
评论列表
已有 0 条评论(查看更多评论)
编辑推荐
package com.mine; import java.net.InetSocketAddress; import java.net.ServerSocket; import jav
package com.mine; import java.net.InetSocketAddress; import java.net.ServerSocket; import jav
package com.mine; import java.net.InetSocketAddress; import java.net.ServerSocket; import jav
这只是长征路上的一小步,以后还有待改进。 NIO Selector示意图: 客户端代码: import java.io.IOE
这只是长征路上的一小步,以后还有待改进。 NIO Selector示意图: 客户端代码: import java.io.IOE
6 nio
1. 基本 概念 IO 是主存和外部设备 ( 硬盘、终端和网络等 ) 拷贝数据的过程。 IO 是操作系统的底层
7 NIO
FROM IBM : developerWorks 中国网站 流与块的比较 原来的 I/O 库(在 java.io.*中) 与 NIO 最重要的
8 nio
Java NIO非堵塞应用通常适用用在I/O读写等方面,我们知道,系统运行的性能瓶颈通常在I/O读写,包括
9 NIO
FROM IBM : developerWorks 中国网站 流与块的比较 原来的 I/O 库(在 java.io.*中) 与 NIO 最重要的
10 NIO
1.NIO&原I/O区别 NIO和原来的I/O最重要的区别是数据打包和传输方式的不同 ----原I/O------以流的方
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号