成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

Java使用Socket通信傳輸文件的方法示例-創(chuàng)新互聯(lián)

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

網(wǎng)站建設哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、小程序設計、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了葉城免費建站歡迎大家使用!

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

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

下面的示例演示了客戶端向服務器端發(fā)送一個文件,服務器作為響應給客戶端回發(fā)一個文件。這里準備兩個文件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) {}
    }
  }
}

本文標題:Java使用Socket通信傳輸文件的方法示例-創(chuàng)新互聯(lián)
路徑分享:http://jinyejixie.com/article10/depcgo.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供用戶體驗、網(wǎng)站改版、品牌網(wǎng)站建設、網(wǎng)站設計公司、手機網(wǎng)站建設定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)
孝感市| 水富县| 三河市| 汝阳县| 濉溪县| 东港市| 宜城市| 英吉沙县| 桃源县| 米脂县| 股票| 怀仁县| 六安市| 福建省| 桦甸市| 松原市| 瓮安县| 浦城县| 安徽省| 邻水| 靖宇县| 宜宾市| 通山县| 康平县| 宣武区| 大足县| 九台市| 潢川县| 巧家县| 顺义区| 穆棱市| 宜丰县| 聂拉木县| 如皋市| 古浪县| 娱乐| 肃南| 香港 | 策勒县| 虞城县| 牟定县|