NIO的简单例子

一个最简单的NIO socket代码:

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ChannelAccept
{
	public static String GREETING = "Hello World\r\n";
	
	public static void main(String[] args)throws Exception
	{
		int port = 1234;
		
		ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());
		
		ServerSocketChannel ssc = ServerSocketChannel.open();
		
		ssc.socket().bind(new InetSocketAddress(port));
		
		ssc.configureBlocking(false);
		
		while(true)
		{
			System.out.println("waiting for connecting....");
			
			SocketChannel sc = ssc.accept();
			
			if(null == sc)
			{
				Thread.sleep(3000);
			}else
			{
				System.out.println("Incoming connecting from : "+sc.socket().getRemoteSocketAddress());
				sc.write(buffer);
				sc.close();
			}
			
		}
		
	}
}


结果:

NIO的简单例子_第1张图片



你可能感兴趣的:(JAVA)