zoukankan      html  css  js  c++  java
  • Java Socket实战之七 使用Socket通信传输文件

    http://blog.csdn.net/kongxx/article/details/7319410

    package com.googlecode.garbagecan.test.socket.nio;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.ClosedChannelException;
    import java.nio.channels.FileChannel;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    public class MyServer4 {

    private final static Logger logger = Logger.getLogger(MyServer4.class.getName());

    public static void main(String[] args) {
    Selector selector = null;
    ServerSocketChannel serverSocketChannel = null;

    try {
    // Selector for incoming time requests
    selector = Selector.open();

    // Create a new server socket and set to non blocking mode
    serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);

    // Bind the server socket to the local host and port
    serverSocketChannel.socket().setReuseAddress(true);
    serverSocketChannel.socket().bind(new InetSocketAddress(10000));

    // Register accepts on the server socket with the selector. This
    // step tells the selector that the socket wants to be put on the
    // ready list when accept operations occur, so allowing multiplexed
    // non-blocking I/O to take place.
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

    // Here's where everything happens. The select method will
    // return when any operations registered above have occurred, the
    // thread has been interrupted, etc.
    while (selector.select() > 0) {
    // Someone is ready for I/O, get the ready keys
    Iterator<SelectionKey> it = selector.selectedKeys().iterator();

    // Walk through the ready keys collection and process date requests.
    while (it.hasNext()) {
    SelectionKey readyKey = it.next();
    it.remove();

    // The key indexes into the selector so you
    // can retrieve the socket that's ready for I/O
    doit((ServerSocketChannel) readyKey.channel());
    }
    }
    } catch (ClosedChannelException ex) {
    logger.log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
    logger.log(Level.SEVERE, null, ex);
    } finally {
    try {
    selector.close();
    } catch(Exception ex) {}
    try {
    serverSocketChannel.close();
    } catch(Exception ex) {}
    }
    }

    private static void doit(final ServerSocketChannel serverSocketChannel) throws IOException {
    SocketChannel socketChannel = null;
    try {
    socketChannel = serverSocketChannel.accept();

    receiveFile(socketChannel, new File("E:/test/server_receive.log"));
    sendFile(socketChannel, new File("E:/test/server_send.log"));
    } finally {
    try {
    socketChannel.close();
    } catch(Exception ex) {}
    }

    }

    private static void receiveFile(SocketChannel socketChannel, File file) throws IOException {
    FileOutputStream fos = null;
    FileChannel channel = null;

    try {
    fos = new FileOutputStream(file);
    channel = fos.getChannel();
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

    int size = 0;
    while ((size = socketChannel.read(buffer)) != -1) {
    buffer.flip();
    if (size > 0) {
    buffer.limit(size);
    channel.write(buffer);
    buffer.clear();
    }
    }
    } finally {
    try {
    channel.close();
    } catch(Exception ex) {}
    try {
    fos.close();
    } catch(Exception ex) {}
    }
    }

    private static void sendFile(SocketChannel socketChannel, File file) throws IOException {
    FileInputStream fis = null;
    FileChannel channel = null;
    try {
    fis = new FileInputStream(file);
    channel = fis.getChannel();
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    int size = 0;
    while ((size = channel.read(buffer)) != -1) {
    buffer.rewind();
    buffer.limit(size);
    socketChannel.write(buffer);
    buffer.clear();
    }
    socketChannel.socket().shutdownOutput();
    } finally {
    try {
    channel.close();
    } catch(Exception ex) {}
    try {
    fis.close();
    } catch(Exception ex) {}
    }
    }
    }

    client

    package com.googlecode.garbagecan.test.socket.nio;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.SocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.channels.SocketChannel;
    import java.util.logging.Level;
    import java.util.logging.Logger;

    public class MyClient4 {

    private final static Logger logger = Logger.getLogger(MyClient4.class.getName());

    public static void main(String[] args) throws Exception {
    new Thread(new MyRunnable()).start();
    }

    private static final class MyRunnable implements Runnable {
    public void run() {
    SocketChannel socketChannel = null;
    try {
    socketChannel = SocketChannel.open();
    SocketAddress socketAddress = new InetSocketAddress("localhost", 10000);
    socketChannel.connect(socketAddress);

    sendFile(socketChannel, new File("E:/test/client_send.log"));
    receiveFile(socketChannel, new File("E:/test/client_receive.log"));
    } catch (Exception ex) {
    logger.log(Level.SEVERE, null, ex);
    } finally {
    try {
    socketChannel.close();
    } catch(Exception ex) {}
    }
    }

    private void sendFile(SocketChannel socketChannel, File file) throws IOException {
    FileInputStream fis = null;
    FileChannel channel = null;
    try {
    fis = new FileInputStream(file);
    channel = fis.getChannel();
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    int size = 0;
    while ((size = channel.read(buffer)) != -1) {
    buffer.rewind();
    buffer.limit(size);
    socketChannel.write(buffer);
    buffer.clear();
    }
    socketChannel.socket().shutdownOutput();
    } finally {
    try {
    channel.close();
    } catch(Exception ex) {}
    try {
    fis.close();
    } catch(Exception ex) {}
    }
    }

    private void receiveFile(SocketChannel socketChannel, File file) throws IOException {
    FileOutputStream fos = null;
    FileChannel channel = null;

    try {
    fos = new FileOutputStream(file);
    channel = fos.getChannel();
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

    int size = 0;
    while ((size = socketChannel.read(buffer)) != -1) {
    buffer.flip();
    if (size > 0) {
    buffer.limit(size);
    channel.write(buffer);
    buffer.clear();
    }
    }
    } finally {
    try {
    channel.close();
    } catch(Exception ex) {}
    try {
    fos.close();
    } catch(Exception ex) {}
    }
    }
    }
    }

  • 相关阅读:
    【译】常用网络端口号列表
    使用Simian进行重复代码检测
    使用GCOV进行代码覆盖率统计
    AFL Fuzz安装及完成一次简单的模糊测试
    数据可视化概述
    完成下方的 which_date() 函数,并返回某一起始时间后特定一段时间的日期
    linux用户不在sudoers文件中
    linux /lib64/libc.so.6: version `GLIBC_2.17′ not found
    web api 2.0 上传文件超过4M时,出现404错误
    Centos7 编译安装 Nginx Mariadb Asp.net Core2 (实测 笔记 Centos 7.7 + Openssl 1.1.1d + Mariadb 10.3.7 + Nginx 1.16.1 + Asp.net. Core 2 )
  • 原文地址:https://www.cnblogs.com/jishumonkey/p/13889858.html
Copyright © 2011-2022 走看看