tionKey selectionKey = sc.register(selector, SelectionKey.OP_WRITE);
//在这个selectionKey上绑定一个对象,以供写操作时取出进行处理
DownloadFileProcesser downloadFileProcesser = new DownloadFileProcesser();
selectionKey.attach(downloadFileProcesser);
}
// 如果客户端有下载文件数据请求
if (s.isWritable()) {
//这里把attachment取出进行写入操作
DownloadFileProcesser downloadFileProcesser = (DownloadFileProcesser)s.attachment();
int count = downloadFileProcesser.readFile2Buffer();
if(count <= 0){
System.out.println("客户端下载完毕...");
//关闭通道
s.channel().close();
downloadFileProcesser.close();
}else{
//需要注意的是我们这里并没有出现常见的while写的结构,这是为何?
//因为client其实不断的在read操作,从而触发了SELECTOR的不断写事件!
SocketChannel sc = (SocketChannel)s.channel();
sc.write(downloadFileProcesser.getByteBuffer());
}
}
iterator.remove();
}
}
}
}
客户端代码:
class Client4DownloadFile implements Runnable{
//标示
private String name;
private FileChannel fileChannel;
public Client4DownloadFile(String name , RandomAccessFile randomAccessFile){
this.name = name;
this.fileChannel = randomAccessFile.getChannel();
}
private ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
@Override
public void run() {
try {
SocketChannel sc = SocketChannel.open();
Selector selector = Selector.open();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_CONNECT);
sc.connect(new InetSocketAddress("127.0.0.1",8887));
while(true){
selector.select();
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey s = iterator.next();
if(s.isConnectable()){
System.out.println("客户端[" + name + "]已经连接上了服务器...");
SocketChannel sc2 = (SocketChannel)s.channel();
if(sc2.isConnectionPending() && sc2.finishConnect()){
sc2.configureBlocking(false);
String msg = "Thread-" + name + " send message!";
byte[] b = msg.getBytes("utf-8");
sc2.write(ByteBuffer.wrap(b));
System.out.println("客户端[" + name + "]给服务器端发送文本消息完毕...");
sc2.register(selector, SelectionKey.OP_READ);
}
}
if(s.isReadable()){
Socke