I am trying to send an image in the form of a byte array from a client application to a server. The server code is written in python while the client is written in java. The image is being transferred correctly however the image saved on the server machine is corrupted.
The following is the code for the server.
import socket
import struct
HOST = "192.168.1.100"
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
print('SERVER STARTED RUNNING')
while True:
client, address = s.accept()
buf = ''
while len(buf) < 4:
buf += client.recv(4 - len(buf))
size = struct.unpack('!i', buf)[0]
with open('/home/isaac/Desktop/image.jpg', 'wb') as f:
while size > 0:
data = client.recv(1024)
f.write(data)
size -= len(data)
print('Image Saved')
client.sendall('Image Received')
client.close()
The following is the source code for the java client:
public static void main(String[] args) throws IOException {
byte[] array = extractBytes("/home/isaac/Desktop/cat.jpg");
Socket sock = new Socket(IP_ADDRESS, PORT_NO);
DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
System.out.println("Array Length - " + array.length);
dos.writeInt(array.length);
dos.write(array);
BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
System.out.println(reader.readLine());
}
Hopefully you can help me. I've tried to google to get my answer but no solution has worked so far.
In what sense you get a corrupted image? I've tried it with the following array:
byte[] array = new byte[3000];
for(int i=0; i<array.length; i++) {
array[i] = (byte)('0' + (i % 10));
}
and I get the same array I sent.
Another thing, just to be sure: the file is less than 2Gb, right?