设为首页 加入收藏

TOP

Java NIO 服务器与客户端实现文件下载(一)
2017-03-30 14:17:55 】 浏览:560
Tags:Java NIO 服务器 客户端 实现 文件下载

写在前面


对于Java NIO已经学习了一段时间了,周末实践了下,折腾了一天,总算对NIO的理论,有了一个感性的认识。下面的实践是:服务器与客户端都采用NIO的方式来实现文件下载。对于传统的SOCKET BIO方式,服务器端会为每个连接上的客户端分配一个Worker线程来进行doWork,而NIO SERVER却没有为每个Socket链接分配线程的必要了,避免了大量的线程所需的上下文切换,借助NIO提供的Selector机制,只需要一个或者几个线程来管理成百上千的SOCKET连接。那么下面我们就来看看吧!


文件下载辅助类


/**
 * 这个类的基本思路是,读取本地文件到缓冲区
 * 因为通道只能操作缓冲区
 */
class DownloadFileProcesser implements Closeable{
private ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
private FileChannel fileChannel ;
public DownloadFileProcesser() {
    try{
        FileInputStream fis = new FileInputStream("e:/tmp/Shell学习笔记.pdf");
        fileChannel = fis.getChannel();
    }catch(Exception e){
        e.printStackTrace();
    }
}
public int readFile2Buffer() throws IOException{
    int count = 0;
    buffer.clear();
    count = fileChannel.read(buffer);
    buffer.flip();
    return count;
}
public ByteBuffer getByteBuffer(){
    return buffer;
}
@Override
public void close() throws IOException {
    fileChannel.close();
}
 
}


服务端代码:


public class ServerMain {
 
public static void main(String[] args) throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.socket().bind(new InetSocketAddress(8887));
    Selector selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
 
    while (true) {
        selector.select();
        Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
        SelectionKey s = iterator.next();
        // 如果客户端有连接请求
        if (s.isAcceptable()) {
        System.out.println("客户端连接请求..");
        ServerSocketChannel ssc = (ServerSocketChannel) s.channel();
        SocketChannel sc = ssc.accept();
        sc.configureBlocking(false);
        sc.register(selector, SelectionKey.OP_READ);
        }
        // 如果客户端有发送数据请求
        if (s.isReadable()) {
        System.out.println("接受客户端发送过来的文本消息...");
        //这里拿出的通道就是ACCEPT上注册的SocketChannel通道
        SocketChannel sc = (SocketChannel) s.channel();
        //要读取数据先要准备好BUFFER缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(8 * 1024);
        //准备BYTE数组,形成输出
        sc.read(buffer);
        byte[] clientByteInfo = new byte[buffer.position()];
        buffer.flip();
        buffer.get(clientByteInfo);
        System.out.println("服务器端收到消息:" + new String(clientByteInfo,"utf-8"));
        //CLIENT下一步的动作就是读取服务器端的文件,因此需要注册写事件
        Selec

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

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目