簡體   English   中英

在 Java 中使用套接字傳輸二進制數據

[英]Transferring binary data using sockets in Java

我正在嘗試在 Java 中創建文件傳輸的客戶端 - 服務器模型,其中客戶端將讀取文件並將數據發送到服務器,服務器將接收數據並將其寫入文件。 我已經看過這篇文章,但它涉及 C。

我寫了一個簡單的算法,它會在文件連接到服務器后立即發送。
這是客戶端的代碼:

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

public class Client {
    public static void main(String args[]) {
        try {
            Socket s = new Socket(args[0], Integer.parseInt(args[1]));
            System.out.println("Connected to " + s.getRemoteSocketAddress());
            DataInputStream din = new DataInputStream(s.getInputStream());
            DataOutputStream dout = new DataOutputStream(s.getOutputStream());
            File file = new File(args[2]);
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int no_of_bytes = 0;
            while ((no_of_bytes = fis.read(buffer)) != -1) {
                dout.write(buffer, 0, no_of_bytes);
            }
        } catch (Exception e) {
            System.err.println(e.getLocalizedMessage());
        }
    }
}

這是服務器的代碼:

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

public class Server {
    public static void main(String args[]) {
        try {
            ServerSocket ss = new ServerSocket(Integer.parseInt(args[0]));
            Socket s = ss.accept();
            System.out.println("Connected to " + s.getRemoteSocketAddress());
            DataInputStream din = new DataInputStream(s.getInputStream());
            DataOutputStream dout = new DataOutputStream(s.getOutputStream());
            File new_file = new File("/home/Puspam/Videos/received.png");
            new_file.createNewFile();
            BufferedWriter bw = new BufferedWriter(new FileWriter(new_file));
            int a;
            while ((a = din.read()) != -1) {
                bw.write((char) a);
            }
            din.close();
            bw.flush();
        } catch (Exception e) {
            System.err.println(e.getLocalizedMessage());
        }
    }
}

運行這兩個程序和一個用於實驗的圖像文件后,我發現文件沒有正確傳輸。 當我嘗試打開接收到的文件時,我 PC 中的圖像查看器軟件顯示它不是有效圖像文件的錯誤。 另外,我可以看到接收到的文件比原始文件大一點。
我在這里犯了什么錯誤?

我以前有過這樣的事情。 嘗試在兩端使用相同類型的輸入/輸出流。 例如,BufferedReader 到 BufferedWriter 等。您將 FileInputStream 與 BufferedWriter 結合使用。 此外,您可能需要在for循環的每次迭代中刷新 BufferedWriter。

暫無
暫無

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

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