자바 NIO-5 비 차단 프로 그래 밍 NIO 기반 의 예

이전에 쓴 것 은 대부분이 NIO 지식 점 이 었 고 인 스 턴 스 를 붙 이지 않 았 으 며 어려워 보일 수 있 습 니 다.다음은 비 차단 에 기반 한 nio 인 스 턴 스 입 니 다.
Server:
/**
 *     
 * 
 * @author Joeson
 * 
 */
public class MyServer
{

	public static void main(String args[]) throws Exception
	{
		MyServer server = new MyServer(8080);
		server.listen();
	}

	//           
	private ByteBuffer send = ByteBuffer.allocate(1024);
	private ByteBuffer receive = ByteBuffer.allocate(1024);

	public int port = 0;

	ServerSocketChannel ssc = null;

	Selector selector = null;

	public MyServer(int port) throws Exception
	{
		//           
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		//          
		serverSocketChannel.configureBlocking(false);
		//                
		ServerSocket serverSocket = serverSocketChannel.socket();
		//        
		serverSocket.bind(new InetSocketAddress(port));
		//   open()    Selector
		selector = Selector.open();

		//    selector,    
		serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		System.out.println("Server Start----8888:");
		
		//           
		send.put("data come from server".getBytes());
	}

	//   
	private void listen() throws IOException
	{
		while (true)
		{
			//      ,           
			selector.select();
			//             。
			Set<SelectionKey> selectionKeys = selector.selectedKeys();
			Iterator<SelectionKey> iterator = selectionKeys.iterator();
			while (iterator.hasNext())
			{
				SelectionKey selectionKey = iterator.next();

				//          remove ,  selector  selectedKeys        
				iterator.remove();
				dealKey(selectionKey);
			}
		}
	}

	//     
	private void dealKey(SelectionKey selectionKey) throws IOException
	{

		ServerSocketChannel server = null;
		SocketChannel client = null;
		String receiveText;
		String sendText;
		int count = 0;

		//                       。
		if (selectionKey.isAcceptable())
		{
			//            。
			server = (ServerSocketChannel) selectionKey.channel();

			//            (   )       。
			client = server.accept();
			//       
			client.configureBlocking(false);
			//    selector,    
			client.register(selector, SelectionKey.OP_READ
					| SelectionKey.OP_WRITE);
		}
		else
			if (selectionKey.isReadable())
			{
				//            。
				client = (SocketChannel) selectionKey.channel();
				//             
				receive.clear();
				//                 
				client.read(receive);

				System.out.println(new String(receive.array()));
				
				selectionKey.interestOps(SelectionKey.OP_WRITE);
			}
			else
				if (selectionKey.isWritable())
				{
					//             
					send.flip();
					//            。
					client = (SocketChannel) selectionKey.channel();

					//      
					client.write(send);
					
					selectionKey.interestOps(SelectionKey.OP_READ);
				}
	}
}

Client:
/**
 *    
 * 
 * @author Joeson
 * 
 */
public class MyClient
{
	public static void main(String args[])
	{
		try
		{
			MyClient client = new MyClient();
			client.work(8085);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	SocketChannel sc = null;

	Selector selector = null;

	//        
	ByteBuffer send = ByteBuffer.wrap("data come from client".getBytes());
	ByteBuffer receive = ByteBuffer.allocate(1024);

	public void work(int port) throws IOException
	{

		try
		{
			sc = SocketChannel.open();
			selector = selector.open();

			//         
			sc.configureBlocking(false);

			sc.connect(new InetSocketAddress("localhost", 8080));

			sc.register(selector, SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);

		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Set<SelectionKey> selectionKeys = null;
		while (true)
		{
			//   
			if (selector.select() == 0)
			{
				continue;
			}

			Iterator<SelectionKey> it = selector.selectedKeys().iterator();

			while (it.hasNext())
			{
				SelectionKey key = it.next();

				//           
				it.remove();
				
				sc = (SocketChannel) key.channel();

				if (key.isConnectable())
				{
					if (sc.isConnectionPending())
					{
						//     ,         
						sc.finishConnect();
						System.out.println("connect completely");

						try
						{
							sc.write(send);
						} catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
//						sc.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
					}

				}
				else
					if (key.isReadable())
					{
						try
						{
							receive.clear();

							sc.read(receive);

							System.out.println(new String(receive.array()));

						} catch (IOException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					else
						if (key.isWritable())
						{
							receive.flip();
							try
							{
								send.flip();
								
								sc.write(send);
							} catch (IOException e)
							{
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

			}// end while

		}// end while(true)

	}// end work()

}

좋은 웹페이지 즐겨찾기