Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send a file from Java to C#

I want to send a binary file from a Java server to a C# client. Here's the code I'm using:

Java server:

    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# client:

        //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();

This code only seems to write the first 69696 bytes of the file. From there it will only write 0 until the end.

Any tips?

Thanks

like image 723
Luis Cruz Avatar asked Apr 20 '26 20:04

Luis Cruz


1 Answers

From MSDN: "Read operation reads as much data as is available, up to the number of bytes specified by the size parameter."

That means that you don't necessarily get as much data as you request, you need to check your self until you got as much data as you expect.

int toRead = (int)length;
int read = 0;
while (toRead > 0)
{
    int noChars = networkStream.Read(buffer, read, toRead);
    read += noChars;
    toRead -= noChars;
}
like image 199
Albin Sunnanbo Avatar answered Apr 23 '26 10:04

Albin Sunnanbo