JAva NIO転送ファイル

16508 ワード

package tools.distributedclient;

import java.io.File;
import java.io.FileInputStream;
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;

/** * NIO    */
public class MasterClient {
    //      
    private Selector selector;

    /** *     Socket  ,               * * @param ip *        ip * @param port *            * @throws IOException */
    public void initClient(String ip, int port) throws IOException {
        //     Socket  
        SocketChannel channel = SocketChannel.open();
        //         
        channel.configureBlocking(false);
        //          
        this.selector = Selector.open();

        //         ,             ,   listen()    
        //  channel.finishConnect();      
        channel.connect(new InetSocketAddress(ip, port));
        //             ,       SelectionKey.OP_CONNECT  。
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    /** *          selector           ,   ,      * * @throws IOException */
    @SuppressWarnings("unchecked")
    public void listen() throws IOException {
        //     selector
        while (true) {
            selector.select();
            //   selector         
            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                //      key,      
                ite.remove();
                //       
                if (key.isConnectable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    //       ,     
                    if (channel.isConnectionPending()) {
                        channel.finishConnect();

                    }
                    //       
                    channel.configureBlocking(false);

                    File file = new File("D:/mysql-5.6.23.zip");
                    FileInputStream input = new FileInputStream(file);
                    byte[] buffer = new byte[256 * 1024];
                    int read = 0;
                    while ((read = input.read(buffer)) != -1) {
                        System.out.println(read);
                        ByteBuffer w = ByteBuffer.wrap(buffer, 0, read);
                        while (w.hasRemaining()) {
                            channel.write(w);
                        }
                    }
                    //               
                    // channel.write(ByteBuffer.wrap(new String("           ")
                    // .getBytes()));

                    //            ,             ,           。
                    channel.register(this.selector, SelectionKey.OP_READ);

                    //         
                } else if (key.isReadable()) {
                    read(key);
                }

            }

        }
    }

    /** *                  * * @param key * @throws IOException */
    public void read(SelectionKey key) throws IOException {
        //      read    
    }

    /** *         * * @throws IOException */
    public static void main(String[] args) throws IOException {
        Thread t = new ClientThread("localhost", 8000);
        Thread t2 = new ClientThread("localhost", 8001);
        t.start();
        t2.start();
    }

}

class ClientThread extends Thread {
    int port;
    String server;

    public ClientThread(String server, int port) {
        this.port = port;
        this.server = server;
    }

    public void run() {
        MasterClient client = new MasterClient();
        try {
            client.initClient(server, port);
            client.listen();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package tools.distributedclient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/** * NIO    */
public class SlaveClient2 {
    //      
    private Selector selector;
    File file ;
    long readed = 0;

    /** *     ServerSocket  ,               * * @param port *        * @throws IOException */
    public void initServer(int port) throws IOException {
        //     ServerSocket  
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        //         
        serverChannel.configureBlocking(false);
        //        ServerSocket   port  
        serverChannel.socket().bind(new InetSocketAddress(port));
        //          
        this.selector = Selector.open();
        //             ,       SelectionKey.OP_ACCEPT  ,      ,
        //        ,selector.select()   ,        selector.select()     。
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    /** *          selector           ,   ,      * * @throws IOException */
    @SuppressWarnings("unchecked")
    public void listen() throws IOException {
        System.out.println("       !");
        //     selector
        while (true) {
            //          ,    ;  ,        
            selector.select();
            //   selector         ,          
            Iterator ite = this.selector.selectedKeys().iterator();
            while (ite.hasNext()) {
                SelectionKey key = (SelectionKey) ite.next();
                //      key,      
                ite.remove();
                //          
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key
                            .channel();
                    //            
                    SocketChannel channel = server.accept();
                    //       
                    channel.configureBlocking(false);

                    //               
                    channel.write(ByteBuffer.wrap(new String("           ")
                            .getBytes()));
                    //            ,             ,           。
                    channel.register(this.selector, SelectionKey.OP_READ);

                    //         
                } else if (key.isReadable()) {
                    read(key);
                }

            }

        }
    }

    /** *                  * * @param key * @throws IOException */
    public void read(SelectionKey key) throws IOException {
        //         :       Socket  
        SocketChannel socketChannel = (SocketChannel) key.channel();
        //         

        FileOutputStream output = new FileOutputStream(file,true);
        byte[] singleBytes = new byte[16 * 1024];
        ByteBuffer singleReadBuffer = ByteBuffer.wrap(singleBytes);
        singleReadBuffer.clear();
        int size = 0;
        while (true) {
            // do a single read
            int read = socketChannel.read(singleReadBuffer);
            if (read == -1) {
                // this means we reached the end of socket stream.
                // close();
                break;
            }
            if (read > 0) {
                System.out.println(read);
                readed += read;
                // flip input buffer
                singleReadBuffer.flip();
                // process input buffer
                output.write(singleReadBuffer.array(), 0, read);
                // clear input buffer
                singleReadBuffer.clear();
            }
            if (read == 0) {
                // since no more data available, just break to wait for
                // more in coming data
                break;
            }
        }
        output.flush();
        // String msg = new String(data).trim();
        System.out.println("       ");
        // ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());
        // channel.write(outBuffer);//          
    }

    /** *         * * @throws IOException */
    public static void main(String[] args) throws IOException {
        SlaveClient2 server = new SlaveClient2();
        server.file = new File("D:/mysql-5.6.23.zip3");
        if(server.file.exists()){
            server.file.delete();
        }
        server.file.createNewFile();
        server.initServer(8001);
        server.listen();
    }

}