Whys is this socket connection not working?

socket
python

(Ruarri Schoeman) #1

I have a lot of experience with socket connections and recently I moved into transferring files as a binary object. However, I can’t get my two laptops to connect to each other. I probably just missed something, but I can’t figure it out. It would be great if someone could help out. Cheers

Sending Code:

import socket
import os

host = "localhost"
port = 5454

print(socket.gethostbyname(socket.gethostname()))

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))

print("Waiting for response...")
text, conn = sock.recvfrom(1024)
text = bytes.decode(text)
print(text)
sock.sendto(str.encode("Connected"), conn)

files = []
for (dirpath, dirnames, filenames) in os.walk("Files"):
    files.extend(filenames)
    print(files)

while len(files) > 0:
    sock.sendto(str.encode("startFile"), conn)
    sock.sendto(str.encode(files[0]), conn)
    file = open(files[0], 'rb')
    while True:
        l = file.read(1024)
        if l:
            sock.sendto(str.encode(l), conn)
            print("Sending " + files[0] + "...")
        else:
            sock.sendto(str.encode("endFile"), conn)
            break

    file.close()
    files.remove(files[0])

sock.sendto(str.encode("endTrans"))
sock.close()

Receiving Code:

import socket
import os

host = input("Type the number displayed on the other screen. \n->")
port = 5454

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect((host, port))
print((host, port))
print("Attempting Connection...")
sock.send(str.encode("Connecting..."))
print("Sent Request")
text = bytes.decode(sock.recv(1024))
print(text)

while True:
    x = bytes.decode(sock.recv(1024))
    if x != "endTrans":
        file = open("Files\\" + x,'wb')
        while True:
            l = bytes.decode(sock.recv(1024))
            if l != "endFile":
                file.write(l)
            else:
                break
        file.close()
    else:
        break

sock.close()

(Ruarri Schoeman) #2

I have solved it. I forgot to change host = “localhost” to host = str(socket.gethostbyname(socket.gethostname()))