java nio 入门

nio是Apache mina的基础,之前学习了一些mina,现在倒过来学习一下nio。

1、服务端开发:

package com.ppt.nio;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
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;
import java.util.Set;

public class TServerSocketChannel {

	private ServerSocketChannel server;
	private Selector selector;
	private int port = 9999;
	private String ip = "127.0.0.1";
	
	public TServerSocketChannel() {
		try {
			init();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private void init() throws Exception{
		server = ServerSocketChannel.open();
		server.configureBlocking(false);
		SocketAddress addr = new InetSocketAddress(ip,port);
		ServerSocket serverSocket = server.socket();
		serverSocket.bind(addr);
		selector = Selector.open();
		server.register(selector, SelectionKey.OP_ACCEPT);
	}
	
	private void listen() throws Exception {
		while(true) {
			try {
				int i = selector.select();
				if(i == 0) {
					continue;
				}
				Set keySet = selector.selectedKeys();
				Iterator it = keySet.iterator();
				while(it.hasNext()) {
					SelectionKey key = it.next();
					handle(key);
					it.remove();
				}
			} catch(Exception e) {
				e.printStackTrace();
			}
			
		}
	}
	
	private void handle(SelectionKey key) throws Exception {
		ServerSocketChannel server = null;
		SocketChannel client = null;
		ByteBuffer rBuffer = ByteBuffer.allocate(1024);
		if(key.isAcceptable()) {
			server = (ServerSocketChannel)key.channel();
			client = server.accept();
			client.configureBlocking(false);
			client.register(selector, SelectionKey.OP_READ);
		} else if(key.isReadable()) {
			client = (SocketChannel)key.channel();
			rBuffer.clear();
			try {
				client.read(rBuffer);
			} catch(Exception e) {
				key.cancel();
				client.socket().close();
				client.close();
				e.printStackTrace();
				return;
			}
			String str = new String(rBuffer.array());
			System.out.println("client: " + str);
			rBuffer.flip();
			client.write(rBuffer);
		} 
	}
	public static void main(String[] args) throws Exception {
		TServerSocketChannel ser = new TServerSocketChannel();
		ser.listen();
	}

}

2、客户端开发:

package com.ppt.nio;

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

public class TSocketChannel {

	private Selector selector;
	private SocketChannel client;
	private int port = 9999;
	private String ip = "127.0.0.1";
	
	public TSocketChannel() {
		try {
			init();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	private void init() throws Exception{
		client = SocketChannel.open();
		client.configureBlocking(false);
		SocketAddress remote = new InetSocketAddress(ip,port);
		client.connect(remote);
		selector = Selector.open();
		client.register(selector, SelectionKey.OP_CONNECT);
	}
	private void work() throws Exception{
		while(true) {
			int i = selector.select();
			if(i == 0) {
				continue;
			}
			Iterator it = selector.keys().iterator();
			while(it.hasNext()) {
				SelectionKey key = it.next();
				handle(key);
			}
		}
	}
	private void handle(SelectionKey key) throws Exception {
		ByteBuffer rBuffer = ByteBuffer.allocate(1024);
		ByteBuffer sBuffer = ByteBuffer.allocate(1024);
		if(key.isConnectable()) {
			SocketChannel socket = (SocketChannel)key.channel();
			socket.finishConnect();
			client.register(selector, SelectionKey.OP_READ);
			String msg = "hello server";
			sBuffer.put(msg.getBytes());
			sBuffer.flip();
			client.write(sBuffer);
		} else if(key.isReadable()) {
			rBuffer.clear();
			int length = client.read(rBuffer);
			String str = new String(rBuffer.array());
			System.out.println(str);
		} 
	}
	
	public static void main(String[] args) throws Exception {
		TSocketChannel client = new TSocketChannel();
		client.work();
	}
}


你可能感兴趣的:(java后台)