2

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.

1 Answer 1

3

your both codes are OK, just one thing. in java code, you are sending size of data first, but in python code, you don't separate it from the image.

the best thing to do is just, not sending the size and start sending by sending the whole image. I mean to comment this line out:

        dos.writeInt(size);

it should solve the problem.

good luck.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.