Since you cannot know the amount of data sent in advance in the general case, it would be better to get the data in pieces and ignore the offset to your large array. Your as-is code does not handle this case very well if the data is larger than your array, or if it is smaller than the array.
A simpler case is to remove the offset currentByte:
InputStream input = socket.getInputStream();
BufferedOutputStream output = new BufferedOutputStream(
new FileOutputStream("test.exe"));
byte[] bytes = new byte[2048];
int bytesRead;
do {
bytesRead = input.read(bytes, 0, bytes.length);
System.out.println("size: " + bytes.length + " read(): " + bytesRead);
if (bytesRead > 0) {
output.write(bytes, 0, bytesRead);
}
} while (bytesRead > -1);
output.close();
socket.close();
input.close();
And I used the following client-side C # code:
if (!args.Any())
{
Console.Error.WriteLine("Usage: send.exe <executable>");
Environment.Exit(-1);
}
using (var client = new TcpClient("localhost", 10101))
using (var file = File.Open(args.First(), FileMode.Open, FileAccess.Read))
{
file.CopyTo(client.GetStream());
}
Client side results:
C:\temp>csc send.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.
C:\temp>send send.exe
C:\temp>
Server side results:
C:\temp>javac.exe Server.java
C:\temp>java Server
size: 2048 read(): 2048
size: 2048 read(): 2048
size: 2048 read(): 512
size: 2048 read(): -1
C:\temp>test.exe
Usage: send.exe <executable>
source
share