java nio
程序员文章站
2022-04-24 10:31:28
...
java NIO不怎么会用,但是有个机制,又避不开,所以在网上抄写了一个模型,发现正好符合自己的需求,故存档☞。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class client3 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
byte[] data = {0x04,0x01,0x00,(byte)0x50,(byte)0x79,(byte)0x0e,(byte)0x75,(byte)0x91,0x00};//发送的握手字节序列
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
Selector selector = Selector.open();
SocketChannel channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(new InetSocketAddress("172.19.65.169", 1080));
channel.register(selector, SelectionKey.OP_CONNECT);
//channel.register(selector, SelectionKey.OP_READ);
//进行信息读取
for(; ;) {
selector.select();
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
//连接事件
if(key.isConnectable()) {
SocketChannel socketChannel = (SocketChannel) key.channel();
if(socketChannel.isConnectionPending())
socketChannel.finishConnect();
socketChannel.write(ByteBuffer.wrap(data));//向服务器发信息,信息中即服务器上的文件名
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("connect...");
}
//读事件
if(key.isReadable()) {
SocketChannel socketChannel = (SocketChannel) key.channel();
byteBuffer.clear();
if(!socketChannel.isConnected())
return ;
int r = socketChannel.read(byteBuffer);
System.out.println("read ...");
//set write able
socketChannel.register(selector, SelectionKey.OP_WRITE);
}
if(key.isWritable())
{
System.out.println("write...");
SocketChannel socketChannel = (SocketChannel) key.channel();
//set write able
socketChannel.register(selector, SelectionKey.OP_READ);
}
}
}
}
}
上一篇: BIO、NIO