1. 程式人生 > >IM即時通訊(四) 檔案傳輸

IM即時通訊(四) 檔案傳輸

服務端

package me.mxzf;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * @Title: FileServer
 * @Dscription: 檔案伺服器
 * @author Deleter
 * @date 2017年3月12日 下午4:22:54
 * @version
1.0 */
public class FileServer { public static void main(String[] args) { int len; String fileName; FileOutputStream fos; try { ServerSocket serverSocket = new ServerSocket(1234); Socket socket = serverSocket.accept(); DataInputStream dis = new
DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream( socket.getOutputStream()); // 讀取檔名 fileName = dis.readUTF(); System.out.println(fileName); // 讀取檔案長度 len = dis.readInt(); System.out.println(len); // 讀取檔案內容
byte[] buff = new byte[len]; dis.read(buff); // 寫出檔案 fos = new FileOutputStream("D:/" + fileName); fos.write(buff); fos.close(); // 反饋客戶端,傳輸結果 dos.writeUTF("傳輸完成"); dos.flush(); // 傳輸完成之後一定記住close掉 // 不然客戶端會等待server的資料過來 // 直到socket超時,導致資料不完整 dos.close(); } catch (IOException e) { e.printStackTrace(); } } }

客戶端

package me.mxzf;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 
 * @Title: FileClient
 * @Dscription: 客戶端
 * @author Deleter
 * @date 2017年3月12日 下午4:23:15
 * @version 1.0
 */
public class FileClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket(InetAddress.getLocalHost(), 1234);
            DataOutputStream dos = new DataOutputStream(
                    socket.getOutputStream());
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            File file = new File("c:/DB.zip");
            // 上傳檔名
            dos.writeUTF(file.getName());
            dos.flush();
            // 獲取檔案長度
            FileInputStream fis = new FileInputStream(file);
            int len = fis.available();
            dos.writeInt(len);
            dos.flush();
            // 檔案內容
            byte[] buff = new byte[len];
            dos.write(fis.read(buff));
            dos.flush();
            // 關閉檔案流
            fis.close();
            // 讀取伺服器反饋資訊
            String content = dis.readUTF();
            dis.close();
            // 列印輸出
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

多執行緒多客戶端檔案傳輸就是:迴圈+執行緒+管理類


感覺比較麻煩的話,可以直接用物件流,但是為了讓初學者能夠更好的理解這些比較乏味的東西,還是要多敲程式碼,雖然這種程式碼的確有些不堪入目,哎呀哎呀,得。