pythonsockets

Online Python sockets


I am trying to make a simple app in Python with sockets, but clients only receive the message "Test" sent from the server if they're in the LAN. I tried to run the client (the server is running on my PC) from my laptop and from my PC. In both cases I received the message "Test", but when a friend tries to connect he doesn't receive the message.

Here is my server.py:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 7908))
s.listen(5)

while True:
    clientsocket, address = s.accept()
    print(f"Connection from {address} established")
    clientsocket.send(bytes("Test", "utf-8"))

And here is my client.py:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("my_public_ip_address", 7908))

print(s.recv(8).decode("utf-8"))

I compile client.py with pyinstaller before sending it, so that the script can run without Python being installed on the machine (I don't even have Python on my laptop).


Solution

  • I guess your friend is outside your LAN: if so you should open/portforward port 7908 on the router to the server. Open port 7908 on the sever PC firewall.

    Your script in this way should work.