设为首页 加入收藏

TOP

Java NIO 服务器与客户端实现文件下载(二)
2017-03-30 14:17:55 】 浏览:562
Tags:Java NIO 服务器 客户端 实现 文件下载
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

首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Netty实践教程 下一篇使用Visual Studio 2017作为Linux..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目