i want to send an Image from my Client (which is a Java Application) over socket to my server, which should be programmed in Python. Unfortunately i am new to Python/Java programming and dont understand moast approaches i found online, but what seemed to work best until now was this:
On client side I did this
String pathname = new String("C:\\Users\\vince\\Pictures\\Saved Pictures\\M249.jpg");
Socket photoSocket = new Socket(IP_ADDRESS, PORT_NO);
DataOutputStream dos = new DataOutputStream(photoSocket.getOutputStream());
FileInputStream fis = new FileInputStream(pathname);
int size = fis.available();
byte[] data = new byte[size];
fis.read(data);
dos.writeInt(size);
dos.write(data);
dos.flush();
dos.close();
fis.close();
photoSocket.close();
Which if I understand correctly just sends Image data in form of bytearray to the receiving Port.
Now on Server (Python) i have this:
import socket # Import socket module
s = socket.socket() # Create a socket object
port = 1234 # Reserve a port for your service.
s.bind(("192.168.178.44", port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
conn, addr = s.accept()
print('client connected ... ', addr)
f = open('tst.jpg', 'wb')
while True:
data = conn.recv(1024)
if not data: break
f.write(data)
print('writing file ....')
f.close()
print("finished writing file")
conn.close()
print('client disconnected')
And it seems to transfer data, because after starting my python server file and then running the java app, my python console goes:
client connected ... ('192.168.178.44', 51061) writing file .... writing file .... writing file .... writing file .... writing file .... writing file .... writing file .... finished writing file client disconnected
And then i have a new file named "tst.jpg", and it has the same size in both paths, but i cannot open it because it is somehow broken or corrupted.
Can you tell me whats wrong, and please also how my code should look like? As i said, im new to programming and vague concepts of what i should do don't help me out much.