java的nio例子



package main;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
//import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;


public class JsonSocketServer{


	private static int PORT = 9090;
		
	public static void main(String[] args) {
		System.out.println("Server try start ..");
		Selector selector = null;
		ServerSocketChannel serverSocketChannel = null;
		
		
		try{

			selector = Selector.open();
			
			serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.configureBlocking(false);
			serverSocketChannel.socket().setReuseAddress(true);
			
			serverSocketChannel.socket().bind(new InetSocketAddress(PORT) );
			//注册可读事件
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
			
			while (selector.select()>0) {//select()可指定超时参数
				Iterator<SelectionKey> it = selector.selectedKeys().iterator();
				while (it.hasNext()) {
					SelectionKey readyKey = it.next();
					it.remove();
					
					handleConnection((ServerSocketChannel) readyKey.channel());
					
				}
			}
		}catch (IOException e){
			System.out.println("IO:"+e.getMessage());
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{
				serverSocketChannel.close();
				selector.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
	}
	
	private static void handleConnection(ServerSocketChannel serverSocketChannel) throws IOException {
		SocketChannel socketChannel = null;
		try{
			socketChannel = serverSocketChannel.accept();
			socketChannel.configureBlocking(false);
			String recvShow = new String(recevceData(socketChannel));
			//System.out.println("recv :"+recvShow);
			sendData(socketChannel);
			
		} catch (IOException e) {
			System.out.println("IO"+e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			socketChannel.close();
		}
	}
	
	private static byte[] recevceData(SocketChannel socketChannel) throws IOException {
		int datagramHead = 4;
		int recvTimes = 5;
		//方法使用的数据类型 ByteBuffer java.nio.channels.SocketChannel.read(ByteBuffer arg0) throws IOException
		ByteBuffer buffer = ByteBuffer.allocate(1500);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		byte[] bytes=null;
		int len,lenInfo=-1,offset=0;
		String s;
		try {
			while(true){

				len = socketChannel.read(buffer);
				if(len<0){
					System.out.println("read return "+len);
					break;
				}
				
				offset += len;

				if(len == 0){
					if(lenInfo + datagramHead <= offset && lenInfo != -1){
						break;
					}
					else {
						
						if(--recvTimes == 0)
							break;
						Thread.sleep(10);
						continue;
					}
				}

				buffer.flip();//复位ByteBuffer.position
				bytes = new byte[len];
				buffer.get(bytes);//把position到limit之间的数据复制到bytes,position会变化
				baos.write(bytes);//将本次接收写入缓冲区
				
				if(lenInfo == -1){
					s = new String(baos.toByteArray());
					lenInfo = Integer.parseInt(s.substring(0,datagramHead));
					//System.out.println("len is "+lenInfo);
					if(lenInfo + datagramHead <= offset){
						break;
					}
				}
				
				buffer.clear();//恢复buffer的初始状态 
			}
			if(len >= 0){
				bytes = baos.toByteArray();
			}
			else {
				bytes = new byte[0];
			}
			
		}catch (IOException e) {
			System.out.println("IO"+e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			baos.close();//关闭缓冲区
		}
		
		
		return bytes;
	}
	
	private static void sendData(SocketChannel socketChannel)throws IOException {
		String responseString = "heeeeeee";
		//将bytes数组内容写入buffer
		ByteBuffer buffer = ByteBuffer.wrap(responseString.getBytes());
		try{
			socketChannel.write(buffer);
		}catch (IOException e) {
			System.out.println("IO:"+e.getMessage());
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}




 

posted on 2016-11-30 17:33  阮減显  阅读(207)  评论(0编辑  收藏  举报

导航