简体   繁体   中英

How can I use python sockets over the internet

I'm building a simple chat app using python and want to use it over the internet. The server is starting on my local machine which has the port already forwarded, and to allow other users to access I provided them with the IP address I got from www.whatismyip.com . However, every time I test the application the client side gets this error:

client_socket.connect((ip,port))
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not 
properly respond after a period of time, or established connection failed because connected host has 
failed to respond

The server side is like this:

import socket

shost = socket.gethostname()
ip = socket.gethostbyname(shost)
port = 5000

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((ip,port))
server_socket.listen()
print(f"Server started on {ip}:{port}")
...

And the client side:

import socket

ip = "41.102.XXX.XX"
port = 5000

username = input("Username : ").encode('utf-8')
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((ip,port))
client_socket.send(username)
...

If you are behind a router/NAT, and the PC where your server is has a LAN IP address, then you have to configure port forwarding in the router/NAT from port 5000 to port 5000 in the local IP address. Other 2 possibilities: 1) the client is not sending the packets to the correct IP address, maybe not through the correct network interface. To check this you can use wireshark in the client machine. 2) there is some firewall rule in the server dropping the incoming messages. This is possible if you're getting the error after more than one minute. This usually happens when after the TCP SYN message there is no TCP SYN/ACK message. And not seeing the SYN/ACK is because the SYN message doesn't get to the server's listening port.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM