Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a C# byte array in Java

I'm transferring a file from a C# client to a Java server using TCP Sockets. On the C# client I convert the file to a byte array for transmission and send it using a NetworkStream.

On the Java server I use the following code to convert the received byte array back into a file;

public void run()  {

       try {

            byte[] byteArrayJAR = new byte[filesize];
            InputStream input = socket.getInputStream();

            FileOutputStream fos = new FileOutputStream(
                    "Controller " + controllerNumber + ".jar");

            BufferedOutputStream output = new BufferedOutputStream(fos);

            int bytesRead = input.read(byteArrayJAR, 0, byteArrayJAR.length);
            int currentByte = bytesRead;

            System.out.println("BytesRead = " + bytesRead);

            do {

                bytesRead = input.read(
                        byteArrayJAR,
                        currentByte,
                        (byteArrayJAR.length - currentByte));

                if (bytesRead >= 0) {

                    currentByte += bytesRead;

                }
            }

            while (bytesRead > -1);

            output.write(byteArrayJAR, 0, currentByte);
            output.flush();
            output.close();
            socket.close();

        }

        catch (IOException e) {

            e.printStackTrace();

        }
}

The code above works if the received byte array comes from a client programmed with Java but for C# clients the code hangs in the do-while loop at the bytesRead = input.read(...) method.

Does anybody know why the code is hanging at this point for a C# client but not a Java client? According to the output from the println message data is definately being received by the InputStream and is read once at the bytesRead variable initialization, but not during the do-while loop.

Any solutions or suggestions for overcoming this problem would be welcome.

Regards,

Midavi.

like image 970
midavi Avatar asked Nov 13 '22 11:11

midavi


1 Answers

You need to send your bytes as sbyte from c# instead of byte.

In addition you should change your do/while loop to a regular while loop. If you have already read everything from the stream in your first call to input.read then you will block on the second call because read will wait for input.

like image 191
Charles Lambert Avatar answered Nov 16 '22 03:11

Charles Lambert