客户端程序
public class NioSelectorClient {
public static void main(String[] args) throws IOException{
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
Selector selector = Selector.open();
channel.connect(new InetSocketAddress("127.0.0.1", 7777));
channel.register(selector,SelectionKey.OP_CONNECT|SelectionKey.OP_READ);
System.out.println("============读===AAAA======");
while(true)
{
int n = selector.select();
if(n==0) continue;
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while(iter.hasNext()){
SelectionKey key = iter.next();
if(key.isConnectable())
{
System.out.println("================连接成功了===============");
}
if( key.isReadable())
{
System.out.println("=========数据来了============");
SocketChannel client = (SocketChannel)key.channel();
ByteBuffer buf = ByteBuffer.allocate(1024);
int a= client.read(buf);
buf.flip();
byte[] b = new byte[a];
System.arraycopy(buf.array(), 0, b, 0, a);
String s = new String(b);
System.out.println("============读描述符有数据了======服务器发来的数据:"+s);
}
iter.remove();
}
}
}
}
服务端程序
public class NioSelectorServer {
public static void main(String[] args) throws IOException {
// 创建一个selector选择器
Selector selector = Selector.open();
SocketChannel clientchannel = null;
// 打开一个通道
ServerSocketChannel serverchannel = ServerSocketChannel.open();
// 使设定non-blocking的方式。
serverchannel.configureBlocking(false);
serverchannel.socket().bind(new InetSocketAddress(7777));
// 向Selector注册Channel及我们有兴趣的事件
serverchannel.register(selector, SelectionKey.OP_ACCEPT);
while(true)
{
int n = selector.select();
if (n != 0)
{
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext())
{
SelectionKey key = (SelectionKey) (it.next());
if (key.isAcceptable())
{
System.out.println("=====服务端========连接了=======");
ServerSocketChannel Serverchannel = (ServerSocketChannel) key.channel();
clientchannel = Serverchannel.accept();
clientchannel.configureBlocking(false);
clientchannel.register(selector, SelectionKey.OP_WRITE);
}
if(key.isWritable())
{
System.out.println("=============服务端===========可写=========");
SocketChannel client = (SocketChannel) key.channel();
String ss = "客户端 你好";
client.write(ByteBuffer.wrap(ss.getBytes()));
}
it.remove();
}
}
}
}
}
在本地运行 为什么客户端一直收不到服务端发来的数据了,到底程序错在哪了 ,请大家帮忙指点,最好将我的错误代码改正过来,万分感谢!!!
接数据那部分做成一个线程