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<SelectionKey> keySet = selector.selectedKeys();
				Iterator<SelectionKey> 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<SelectionKey> 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();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值