===
服务端
package 新型IO;
import java.awt.font.TextHitInfo;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.nio.channels.ServerSocketChannel;
public class _004_NIO和Socket
{
public static void main(String[] args) throws Exception
{
//开启服务器socket通道 但是未绑定
ServerSocketChannel ssc1=ServerSocketChannel.open();
//创建绑定地址
SocketAddress addr1=new InetSocketAddress("localhost", 8888);
//进行绑定
ssc1.bind(addr1);
//配置非阻塞模式
ssc1.configureBlocking(false);
while(true)
{
if(ssc1.accept()!=null)//因为是非阻塞模式.所以要循环,不然程序就结束了
{
System.out.println("连接成功");
break;
}
Thread.sleep(2000);
System.out.println("等待连接");
}
}
}
客户端
package 新型IO;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class _004_client
{
public static void main(String[] args) throws Exception
{
//开启SocketChannel
SocketChannel sc1=SocketChannel.open();
//创建连接地址
InetSocketAddress addr1=new InetSocketAddress("localhost", 8888);
//进行连接
boolean b=sc1.connect(addr1);
}
}