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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With