笔记-简单的Nio编程Demo

143 阅读1分钟

服务器端 NioServer.java

public class NioServer {
	private ByteBuffer buf;
	
	public static void main(String[] args) throws IOException {
		NioServer server = new NioServer();
		server.start();
	}

	public void start() throws IOException {
		ServerSocketChannel ssc = ServerSocketChannel.open();
		ServerSocket socket = ssc.socket();

		socket.bind(new InetSocketAddress("localhost", 50000));
		ssc.configureBlocking(false);
		Selector sel = Selector.open();
		ssc.register(sel, SelectionKey.OP_ACCEPT);
		
		System.out.println("start server.");

		while (true) {
			sel.select();
			Set<SelectionKey> keys = sel.selectedKeys();
			Iterator<SelectionKey> it = keys.iterator();
			while (it.hasNext()) {
				SelectionKey key = it.next();
				handleEvent(sel, it, key);
			}
		}

	}

	private void handleEvent(Selector sel, Iterator<SelectionKey> it, SelectionKey key)
			throws IOException, ClosedChannelException {
		if (key.isValid() && key.isAcceptable()) {
			ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
			
			SocketChannel sc = ssc.accept();
			System.out.println("accepted.");
			sc.configureBlocking(false);
			sc.register(sel, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
			it.remove();
		}
		
		if (key.isValid() && key.isReadable()){
			try {
				System.out.println("start read..");
				SocketChannel sc = (SocketChannel) key.channel();
				buf = ByteBuffer.allocate(1024);
				
				int cnt = sc.read(buf);
				
				if (cnt == -1) {
					sc.close();
					return;
				}
				
				System.out.println("Received message from " + sc.getRemoteAddress() + ":" + new String(buf.array()));	
				buf.clear();
				buf.put(new String("hello client.").getBytes());
				buf.flip();
				sc.write(buf);
				buf.clear();
				it.remove();
			} catch (IOException e) {
				e.printStackTrace();
				SocketChannel sc = (SocketChannel) key.channel();
				sc.close();
			}
		}
	}
}

客户端 NioClient.java

public class NioClient {
	private SocketChannel sc;
	private ByteBuffer buf = ByteBuffer.allocate(1024);

	public void connect() throws IOException, InterruptedException {
		sc = SocketChannel.open();
		sc.configureBlocking(false);
		InetSocketAddress adr = new InetSocketAddress("localhost", 50000);
		sc.connect(adr);
		System.out.println("connect to server");
		
		while(!sc.finishConnect()) {
			Thread.sleep(300);
		}
	}
	
	public void read() throws IOException {
		Selector sel = Selector.open();
		
		sc.register(sel, SelectionKey.OP_READ);
		
		while(true) {
			sel.select();
			Set<SelectionKey> keys =  sel.selectedKeys();
			Iterator<SelectionKey> it = keys.iterator();
			
			while(it.hasNext()) {
				SelectionKey key = it.next();
				
				if (key.isValid() && key.isReadable()) {
					read(key);
					it.remove();
				}
			}
		}
	}
	
	public void read(SelectionKey key) throws IOException {
		SocketChannel sc = (SocketChannel) key.channel();
		buf.clear();
		int cnt = sc.read(buf);
		if (cnt < 0) {
			return;
		}
		
		key.channel().close();
		key.cancel();
		
		System.out.println(new String(buf.array()));
	}
	
	public void write(String s) throws IOException {
		buf.put(s.getBytes());
		buf.flip();
		
		while(buf.hasRemaining()) {
			sc.write(buf);
		}
	}
	
	public static void main(String[] args) throws IOException, InterruptedException {
		NioClient cl = new NioClient();
		cl.connect();
		cl.write("hello server.");
		cl.read();
	}
}