Unable to use sockets to send data over the internet in python

363 views Asked by At

I am trying to write a script to transmit an image over the internet using sockets (the code is shown below). When I try it on the local machine the code works fine but when I do the same with 2 different computers (1 working as a server and 1 as client) connected to the same WiFi network, they don't even connect to one another let alone transmit data. Can anyone please help?

The server code :-

import socket
import base64
import sys
import pickle

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 8487))
s.listen(5)
while True:
    # After the Connection is established
    (clientsocket, address) = s.accept()
    print(f"Connection form {address} has been established!")
    # Initiate image conversion into a string
    with open("t.jpeg", "rb") as imageFile:
        string = base64.b64encode(imageFile.read())
        msg = pickle.dumps(string)
        print("Converted image to string")
        # Send the converted string via socket encoding it in utf-8 format
        clientsocket.send(msg)
        clientsocket.close()

        # Send a message that the string is sent
        print("String sent")
        sys.exit()

The client code :-

import socket, pickle, base64

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 8487))

while True:
    data = []
    # Recieve the message
    while True:
        packet = s.recv(1000000)
        if not packet:
            break
        data.append(packet)
        print("Message recieved")

    # Decode the recieved message using pickle
    print("Converting message to a String")
    string = pickle.loads(b"".join(data))
    print("Converted message to String")

    # Convert the recieved message to image
    imgdata = base64.b64decode(string)
    filename = 'tu.jpeg'
    with open(filename, 'wb') as f:
        f.write(imgdata)
    s.shutdown()
    s.close()
1

There are 1 answers

2
Steffen Ullrich On
 s.connect((socket.gethostname(), 8487))

Your client attempts to connect to the local host. If the server host is the local host this works. But if the server host is different this will of course not connect to the server. Instead you have to provide the IP address or hostname of the servers system here.