亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java使用Socket通信傳輸文件的方法示例

發布時間:2020-09-28 13:46:12 來源:腳本之家 閱讀:134 作者:kongxx 欄目:編程語言

本文實例講述了Java使用Socket通信傳輸文件的方法。分享給大家供大家參考,具體如下:

前面幾篇文章介紹了使用Java的Socket編程和NIO包在Socket中的應用,這篇文章說說怎樣利用Socket編程來實現簡單的文件傳輸。

這里由于前面一片文章介紹了NIO在Socket中的應用,所以這里在讀寫文件的時候也繼續使用NIO包,所以代碼看起來會比直接使用流的方式稍微復雜一點點。

下面的示例演示了客戶端向服務器端發送一個文件,服務器作為響應給客戶端回發一個文件。這里準備兩個文件E:/test/server_send.log和E:/test/client.send.log文件,在測試完畢后在客戶端和服務器相同目錄下會多出兩個文件E:/test/server_receive.log和E:/test/client.receive.log文件。

下面首先來看看Server類,主要關注其中的sendFile和receiveFile方法。

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程序代碼,也主要關注sendFile和receiveFile方法

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) {}
      }
    }
  }
}

首先運行MyServer4類啟動監聽,然后運行MyClient4類來向服務器發送文件以及接受服務器響應文件。運行完后,分別檢查服務器和客戶端接收到的文件。

更多關于java相關內容感興趣的讀者可查看本站專題:《Java Socket編程技巧總結》、《Java文件與目錄操作技巧匯總》、《Java數據結構與算法教程》、《Java操作DOM節點技巧總結》和《Java緩存操作技巧匯總》

希望本文所述對大家java程序設計有所幫助。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

宁城县| 新营市| 皮山县| 象州县| 洛南县| 义乌市| 天台县| 清流县| 察哈| 巩留县| 琼中| 布尔津县| 长白| 白银市| 平泉县| 岑溪市| 烟台市| 肃宁县| 高青县| 稷山县| 新泰市| 喜德县| 辛集市| 保靖县| 兴安县| 衡阳县| 乡城县| 白玉县| 长武县| 靖边县| 伊宁县| 海原县| 特克斯县| 永昌县| 湾仔区| 晋州市| 区。| 蓝山县| 闽清县| 铅山县| 英超|