首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Socket 文件傳輸完整實現教程

     編輯:Java 相關知識

概述

本文通過完整的代碼示例,展示如何使用 Java Socket 實現伺服器與客戶端之間的文件傳輸功能。包含伺服器端、客戶端及通用工具類的實現。

1. 伺服器端實現

伺服器監聽指定端口,接受客戶端連接後,讀取本地文件並通過輸出流發送給客戶端。

package sterning;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerTest {
    int port = 8821;

    void start() {
        Socket s = null;
        try {
            ServerSocket ss = new ServerSocket(port);
            while (true) {
                // 待傳輸文件路徑
                String filePath = "D:\\lib.rar";
                File fi = new File(filePath);
                System.out.println("文件長度:" + (int) fi.length());

                // 阻塞等待客戶端連接
                s = ss.accept();
                System.out.println("建立 socket 連接");

                DataInputStream dis = new DataInputStream(new BufferedInputStream(s.getInputStream()));
                dis.readByte(); // 簡單握手

                DataInputStream fis = new DataInputStream(new BufferedInputStream(new FileInputStream(filePath)));
                DataOutputStream ps = new DataOutputStream(s.getOutputStream());

                // 發送文件名與長度
                ps.writeUTF(fi.getName());
                ps.flush();
                ps.writeLong((long) fi.length());
                ps.flush();

                // 分塊發送文件內容
                int bufferSize = 8192;
                byte[] buf = new byte[bufferSize];
                while (true) {
                    int read = 0;
                    if (fis != null) {
                        read = fis.read(buf);
                    }
                    if (read == -1) {
                        break;
                    }
                    ps.write(buf, 0, read);
                }
                ps.flush();

                // 關閉資源
                fis.close();
                s.close();
                System.out.println("文件傳輸完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String arg[]) {
        new ServerTest().start();
    }
}

2. Socket 通用工具類

封裝連接建立、消息發送、流獲取與關閉等通用操作。

package sterning;

import java.io.*;
import java.net.*;

public class ClientSocket {
    private String ip;
    private int port;
    private Socket socket = null;
    DataOutputStream out = null;
    DataInputStream getMessageStream = null;

    public ClientSocket(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void CreateConnection() throws Exception {
        try {
            socket = new Socket(ip, port);
        } catch (Exception e) {
            e.printStackTrace();
            if (socket != null) socket.close();
            throw e;
        }
    }

    public void sendMessage(String sendMessage) throws Exception {
        try {
            out = new DataOutputStream(socket.getOutputStream());
            if (sendMessage.equals("Windows")) {
                out.writeByte(0x1);
                out.flush();
                return;
            }
            if (sendMessage.equals("Unix")) {
                out.writeByte(0x2);
                out.flush();
                return;
            }
            if (sendMessage.equals("Linux")) {
                out.writeByte(0x3);
                out.flush();
            } else {
                out.writeUTF(sendMessage);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (out != null) out.close();
            throw e;
        }
    }

    public DataInputStream getMessageStream() throws Exception {
        try {
            getMessageStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            return getMessageStream;
        } catch (Exception e) {
            e.printStackTrace();
            if (getMessageStream != null) getMessageStream.close();
            throw e;
        }
    }

    public void shutDownConnection() {
        try {
            if (out != null) out.close();
            if (getMessageStream != null) getMessageStream.close();
            if (socket != null) socket.close();
        } catch (Exception e) { }
    }
}

3. 客戶端實現

客戶端連接伺服器,發送簡單指令後接收文件流並保存到本地。

package sterning;

import java.io.*;

public class ClientTest {
    private ClientSocket cs = null;
    private String ip = "localhost";
    private int port = 8821;
    private String sendMessage = "Windows";

    public ClientTest() {
        try {
            if (createConnection()) {
                sendMessage();
                getMessage();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private boolean createConnection() {
        cs = new ClientSocket(ip, port);
        try {
            cs.CreateConnection();
            System.out.print("連接伺服器成功!" + "\n");
            return true;
        } catch (Exception e) {
            System.out.print("連接伺服器失敗!" + "\n");
            return false;
        }
    }

    private void sendMessage() {
        if (cs == null) return;
        try {
            cs.sendMessage(sendMessage);
        } catch (Exception e) {
            System.out.print("發送消息失敗!" + "\n");
        }
    }

    private void getMessage() {
        if (cs == null) return;
        DataInputStream inputStream = null;
        try {
            inputStream = cs.getMessageStream();
        } catch (Exception e) {
            System.out.print("接收消息緩存錯誤\n");
            return;
        }
        try {
            String savePath = "E:\\";
            int bufferSize = 8192;
            byte[] buf = new byte[bufferSize];
            int passedlen = 0;
            long len = 0;

            savePath += inputStream.readUTF(); // 文件名由伺服器傳來
            DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(savePath)));
            len = inputStream.readLong();
            System.out.println("文件的長度為:" + len + "\n");
            System.out.println("開始接收文件!" + "\n");

            while (true) {
                int read = 0;
                if (inputStream != null) {
                    read = inputStream.read(buf);
                }
                passedlen += read;
                if (read == -1) {
                    break;
                }
                System.out.println("文件接收了" + (passedlen * 100 / len) + "%\n");
                fileOut.write(buf, 0, read);
            }
            System.out.println("接收完成,文件存為" + savePath + "\n");
            fileOut.close();
        } catch (Exception e) {
            System.out.println("接收消息錯誤" + "\n");
            return;
        }
    }

    public static void main(String arg[]) {
        new ClientTest();
    }
}

關鍵點總結

  • 伺服器端使用 ServerSocket.accept() 阻塞等待連接。
  • 傳輸協議:先發送文件名、文件長度,再發送二進制內容。
  • 使用 BufferedInputStream/OutputStream 提高 I/O 效率。
  • 傳輸結束後必須正確關閉 Socket,否則客戶端會一直等待導致數據不全。
  • 真實項目中應增加異常處理、斷點續傳、多線程併發等增強功能。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved