Transfer bitmap from C# server program over TcpClient to Java Socket gets corrupted

Server program C#

private TcpListener serverSocket;
..
init:

serverSocket = new TcpListener(ipAddress, port_number);

when new connection request found:

TcpClient clientSock = default(TcpClient);
clientSock = serverSocket.AcceptTcpClient();
NetworkStream networkStream = clientSocket.GetStream();
String FileName = requested binary data file name from client
Byte[] sendBytes = null;
if (File.Exists(pkgName))
{
//load file contents
sendBytes = File.ReadAllBytes(pkgName);
}
if (sendBytes != null)
{
    networkStream.Write(sendBytes, 0, sendBytes.Length); //sendBytes.Length = 1001883;
    networkStream.Flush();
}
...

Java Android code: client

InetAddress serverAddr = InetAddress.getByName(serverIp);
Log.d("SideloadManager", "C: Connecting...");

Socket socket = new Socket(serverAddr, serverPort);

InputStream inFromServer = socket.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);

FileOutputStream outStream = new FileOutputStream("...\recieved.bmp");
int size = 1001883; //same size from server
byte[] buf = new byte[size];
in.read(buf);   
outStream.write(buf, 0, buf.length);
outStream.flush();
outStream.close();

received.bmp is of same size as on server 1001883 bytes. But its contents gets corrupted. After debugging i have seen that: on C# program byte array is [ 149, 145, 10, .....] on Java program byte array is: [ -105, -101, 10, .....] this is due to signed byte in java

What am i missing to receive correct bitmap?

SOLVED as below:

Replace:

int size = 1001883; //same size from server
byte[] buf = new byte[size];
in.read(buf);   
outStream.write(buf, 0, buf.length);

with this:

int len=-1;             
byte[] buf = new byte[1024];
while ((len = in.read(buf, 0, buf.length)) > 0) {
   outStream.write(buf, 0, len);
}

solved the issue :)

Answers


The data is transferred correctly because 149 and -105 have the same binary representation as bytes. The more likely problem is that you're not reading all of the data that was sent in the java side.

The read method returns the number of bytes that have been read, and -1 when the end of the stream has been reached. You need a loop to read the entire file:

int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
    outStream.write(buf, 0, bytesRead);
}

Need Your Help

clarification on the concept of "web service"

java web-services soap wsdl axis

Im a little confused on the varying definitions and implementations of web services available as implementations. Need some clarification please.

How to get the size of UILabel from a dynamic UITableView cell?

ios xcode swift uilabel ios9

I am trying to place a bubble imageView as a superview of a label. The tv cell is dynamical and so the label. I can't get the right width and height of the label in order to change the frame of the