3

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

Java服务器:

    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 直到结束。

有小费吗?

谢谢

4

2 回答 2

4

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

这意味着您不一定会获得所需的数据,您需要检查自己,直到获得与预期一样多的数据。

int toRead = (int)length;
int read = 0;
while (toRead > 0)
{
    int noChars = networkStream.Read(buffer, read, toRead);
    read += noChars;
    toRead -= noChars;
}
于 2012-04-12T18:16:02.313 回答
0

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

同样适用于客户端。

于 2012-04-12T18:18:55.103 回答