簡體   English   中英

通過Java套接字發送文件時出錯

[英]Error sending file through java socket

我通過套接字Java發送文件時遇到問題。 有時代碼有效,有時無效。 我在兩者中都測試了while塊,似乎代碼正在發送所有字節,但服務器未接收到(但即使在此測試中,文件也已正確發送)。 在這種情況下,服務器停止接收數據。 所有文件約為150Kb。 我正在使用端口9191。

服務器:

while (true) {
        try {
            Socket socket = ss.accept();
            ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
            String fileName = in.readUTF();

            FileOutputStream fos = new FileOutputStream(destinationPath + fileName);
            byte[] buf = new byte[1024];

            int len;
            while ((len = in.read(buf)) >= 0) {
                fos.write(buf, 0, len);
            }
            fos.flush();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
}

客戶:

    try {
        Socket socket = new Socket(host, port);
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());

        out.writeUTF(file.getName());
        out.writeLong(file.length());
        FileInputStream in = new FileInputStream(file);
        byte[] buf = new byte[1024];

        int len;
        while ((len = in.read(buf)) >= 0) {
            out.write(buf, 0, len);
        }

        out.close();
        socket.close();

    } catch (Exception e) {
        throw e;
    }

首先,您應該分別用DataInputStreamDataOutputStream替換ObjectInputStreamObjectOutputStream 您不是在序列化Java對象,並且使用用於此目的的流類沒有任何意義。

其次,您要在客戶端中發送文件長度,而不是在服務器中專門讀取它。 而是將其添加到文件的開頭。

在客戶你說,

out.writeUTF(file.getName());
out.writeLong(file.length());

但是您在服務器上說

String fileName = in.readUTF();
FileOutputStream fos = new FileOutputStream(destinationPath + fileName);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) >= 0) {
    fos.write(buf, 0, len);
}
fos.flush();

您沒有閱讀文件長度。 並且您需要確保讀取了所有已發送的字節(否則文件將被破壞)。 另外,不要忘記close() FileOutputStream (或使用try-with-resources為您關閉它)。 就像是,

String fileName = in.readUTF();
try (FileOutputStream fos = new FileOutputStream(destinationPath
        + fileName)) {
    long size = in.readLong();
    byte[] buf = new byte[1024];
    long total = 0;
    int len;
    while ((len = in.read(buf)) >= 0) {
        fos.write(buf, 0, len);
        total += len;
    }
    if (total != size) {
        System.err.printf("Expected %d bytes, but received %d bytes%n",
                size, total);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM