Skip to content Skip to sidebar Skip to footer

Python Socket Communication Across Networks Not Working

I'm trying to set up communication between me and my friend's computer using the socket module. I run the server code on my computer and he runs the client code on his computer. He

Solution 1:

Okay I setup a HotSpot my Android Phone. which in this case is your "Router", used my phone's IP Address. and On the computer tried to run your client code, its sending test messages on the client:

Sending: Test message Sending: Test message Sending: Test message Sending: Test message ....

but I'm receiving nothing on your Server, still saying server started.

so I configured your host variable on the "Client App" like so, also your ports are not consistent 2000 on server and 2001 on client:

host = "" # External IP of my router port = 2000 NOTE!! I left the host Empty

Because I think for some reason the server is hosted locally on the pc, you are running the server on. This way i can also Connect locally from the same computer I ran the server app with:

host = "localhost" # External IP of my router

on the your client app.

this is how everything looks.

Server Code run this on your comuter.

import socket

host = "" # IP of my computer
port = 2000

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

addrs = []

print("Server started")
while True:
    data, addr = s.recvfrom(1024)
    if not addr in addrs:
        addrs.append(addr)
    data = data.decode("utf-8")
    print("Recieved: " + str(data))
    print("Sending: " + data)
    for add in addrs:
        s.sendto(data.encode("utf-8"), add)

Depending on where you ran your serverApp. use the IP of the computer running the server. I'm Still learning so I don't know how to set it up to use your router's IP.

ClientApp Code run this on your friend computer or more. or on android even.

import socket
import time

host = "ip_of_the_computer_the_server_is_running_on"# connecting from another computer#host = "localhost" # If you connecting locally

port = 2000

server = (host, port)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setblocking(False)

whileTrue:
    message = "Test message"
    time.sleep(1)
    print("Sending: " + message)
    s.sendto(message.encode("utf-8"), server)
    try:
        data, addr = s.recvfrom(1024)
    except BlockingIOError:
        passelse:
        data = data.decode("utf-8")
        print("Recieved: " + str(data))

And use Your router only for same AP Connection. Tested with my TOTO-LINK IT WORKS FINE. as long as I don't use my router's IP On the client host.

DemonstrationsServerServer Code Running and recieving from Android and localhost

CLient

Client on computer Sending Tests

Client On Mobileenter image description here

Solution 2:

This code is actually 100% correct, the error was in my port forwarding.

Post a Comment for "Python Socket Communication Across Networks Not Working"