将文件从 Java 发送到 C#

本文关键字:Java 文件 | 更新日期: 2023-09-27 18:31:07

我想将二进制文件从 Java 服务器发送到 C# 客户端。这是我使用的代码:

爪哇服务器:

    ServerSocket serverSocket = new ServerSocket(1592);
    Socket socket = serverSocket.accept();
    PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
    File file = new File("img.jpg");
    //send file length
    out.println(file.length());
    //read file to buffer
    byte[] buffer = new byte[(int)file.length()];
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    dis.read(buffer, 0, buffer.length);
    //send file
    BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
    bos.write(buffer);
    bos.flush();
    Thread.sleep(2000);

C# 客户端:

        //connect to server
        TcpClient tcpClient = new TcpClient();
        tcpClient.Connect("127.0.0.1", 1592);
        NetworkStream networkStream = tcpClient.GetStream();
        StreamReader sr = new StreamReader(networkStream);
        //read file length
        int length = int.Parse(sr.ReadLine());
        Console.WriteLine("File size: {0} bytes", length);
        //read bytes to buffer
        byte[] buffer = new byte[length];
        networkStream.Read(buffer, 0, (int)length);
        //write to file
        BinaryWriter bWrite = new BinaryWriter(File.Open("C:/img.jpg", FileMode.Create));
        bWrite.Write(buffer);
        bWrite.Flush();
        bWrite.Close();

此代码似乎只写入文件的前 69696 字节。从那里它只会写 0 直到最后。

有什么提示吗?

谢谢

将文件从 Java 发送到 C#

来自 MSDN:"读取操作读取尽可能多的可用数据,最多读取 size 参数指定的字节数。

这意味着您不一定会获得您请求的那么多数据,您需要检查自己,直到您获得预期的尽可能多的数据。

int toRead = (int)length;
int read = 0;
while (toRead > 0)
{
    int noChars = networkStream.Read(buffer, read, toRead);
    read += noChars;
    toRead -= noChars;
}

检查您的 DataInputStream 实际读取了多少字节,它可能小于您分配的数组的长度。

这同样适用于客户端。