java nio demo

server:


package nio;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

import com.utils.Util;

public class NioServer implements Runnable{

	boolean bDebugPrint = false;
	
	static int port = 0;
	
	ServerSocket serverSoc;	
	InetSocketAddress address;
	
	ServerSocketChannel serverChannel;
	Selector selector;
	
	Command commander = null;
	
	
	
	@Override
	public void run() {
		
		if (port == 0) {
			Util.print("port not set");
			return;
		}
		
		try {
			selector = Selector.open();
			
			serverChannel = ServerSocketChannel.open();
			serverChannel.configureBlocking(false);
			
			serverSoc = serverChannel.socket();
			address = new InetSocketAddress(port);
			serverSoc.bind(address);
			
			SelectionKey key = 
					serverChannel.register(selector, SelectionKey.OP_ACCEPT);
			
			while (true) {
				int num = selector.select();
				
				Set selectedKey = selector.selectedKeys();
				Iterator it = selectedKey.iterator();
				while (it.hasNext()) {
					key = (SelectionKey)it.next();
					
					if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {
						ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
						SocketChannel sc = ssc.accept();
						sc.configureBlocking(false);
						SelectionKey newKey = sc.register(selector, SelectionKey.OP_READ);
						//Util.print("accept a new socket : " + sc.socket());
					} else if ((key.readyOps() & SelectionKey.OP_READ)
							== SelectionKey.OP_READ){
						SocketChannel sc = (SocketChannel)key.channel();
						
						//Util.print("server read event");
						
						ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
						byteBuffer.position(0);
						int len = sc.read(byteBuffer);
						
						if (len > 0) {
							byte[] data = new byte[len];
							for (int i = 0; i < len; i++) {
								data[i] = byteBuffer.get(i);
							}
							
							if (bDebugPrint) {
								Util.print(new String(data));
							}
							
							if (commander != null) {
								commander.invoke(new String(data));
							}	
						}
					}
					
					it.remove();//very important!
				}
			
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	public void setCommander(Command cd) {
		this.commander = cd;
	}

	public boolean isbDebugPrint() {
		return bDebugPrint;
	}

	public void setbDebugPrint(boolean bDebugPrint) {
		this.bDebugPrint = bDebugPrint;
	}
	
	public void setPort(int port) {
		this.port = port;
	}
	
}



client:

package nio;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.*;

import com.utils.Util;

public class NioClient {

	boolean DEBUG = true;
	
	String hostName;
	int port;
	SocketChannel socketChannel;
	Selector selector;
	
	
	public	NioClient(String hostName, int port, boolean bStartLoop) {
		this.hostName = hostName;
		this.port = port;
		try {
			socketChannel = SocketChannel.open(new InetSocketAddress(hostName, port));
			socketChannel.configureBlocking(false);
			
			selector = Selector.open();
			socketChannel.register(selector, SelectionKey.OP_READ);
			
			if (!bStartLoop) {
				new Thread() {
					public void run() {
						if (DEBUG) {
							Util.print("start loop.");
						}
						
						loop();
					}
				}.start();
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
			
	}
	
	private void loop() {
		while (true) {
			try {
				int num = selector.select();
				
				Set selectedKey = selector.selectedKeys();
				Iterator itor = selectedKey.iterator();
				while (itor.hasNext()) {
					SelectionKey key = (SelectionKey)itor.next();
					
					if ((SelectionKey.OP_READ & key.readyOps()) == SelectionKey.OP_READ) {
						if (DEBUG) {
							Util.print("read event.");
						}
						
						SocketChannel sc = (SocketChannel)key.channel();
						BufferedReader reader 
							= new BufferedReader(new InputStreamReader(sc.socket().getInputStream()));
						String strLine;
						while (null != (strLine = reader.readLine())) {
							Util.print(strLine);
						}
					}
					
					itor.remove();	//very important!
				}
				
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		}
	}
	
	
	public void send(String str) {
		try {
			ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
			socketChannel.write(byteBuffer);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void close() {
		try {
			socketChannel.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值