将文件从Java发送到C#

提问

我想从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直到结束.

有小费吗?

谢谢

最佳答案

MSDN开始:“读取操作将读取尽可能多的数据,最大为size参数指定的字节数.”

这意味着您不一定会获得所需的尽可能多的数据,而是需要检查自己,直到获得所需的尽可能多的数据.

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