简体   繁体   中英

Server/Client application TimeoutError on LAN

I have two programs: server.py and client.py. I need to be able to use server.py in my main PC, and client.py from my laptop. When I run them, I get the following error from client.py:

TimeoutError: [WinError 10060]

I have disabled firewalls in both my PC (that runs Windows 7) and my laptop (that runs Windows 8).

How do I get them to connect?

Some things that I have tried:

  • Creating Firewall port rules, on the PC.
  • Disabling the firewall in both computers.
  • Using different ports.
  • Changing the server address from "localhost" to socket.gethostname(), this changes the error from TimeoutError to ConnectionRefusedError .

The IP for my PC is 192.168.0.2, and I am sure of this because I have an Apache server running in port 80, and that one works (I can access that from my laptop).

Python versions: PC: 3.5.2, Laptop: 3.4.1

Code

server.py:

import socket
import threading

server_port = 2569
server_address = "localhost"

class ClientThread(threading.Thread):
    def __init__(self, client_info):
        super(ClientThread, self).__init__()
        self.client_info = client_info

    def run(self):
        socket = self.client_info[0]
        bytes_received = socket.recv(100)
        print(bytes_received.decode("utf-8"))

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((server_address, server_port))
server_socket.listen(5)

while True:
    new_client = server_socket.accept()
    ClientThread(new_client).run()

client.py:

import socket

server_port = 2569
server_address = "192.168.0.2"

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((server_address, server_port))
server_socket.send(b"message")

You just need to change the localhost or socket.gethostname() in the server.py/client.py scripts to the actual internal ip address of the server. Then it will work!

If you want to learn more why this happens I recommend reading this post which explains in deep the differences between localhost/127.0.0.1 and the internal ip of a machine, which are falsely considered to be the same thing, but in fact they are not.

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