You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Python Socket两台同网电脑连接失败,如何解决?

局域网内Windows机器间Socket连接超时问题

我尝试使用Python的Socket模块在同一局域网内的两台Windows电脑间建立连接,但客户端始终无法连接到服务器,程序提示服务器响应超时。已尝试输入服务器IP、使用localhost、关闭防火墙等操作,均未解决问题。

服务器端代码

#Server

#Socket TCP
import socket
import os

#Criando o socket
host=socket.gethostbyname(socket.gethostname())
port=7000
BUFFER_SIZE=1024

print("Servidor a la escucha por el puerto: ",port, " en la direccion: ",host)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socketTCP:
    socketTCP.bind((host,port)) #dar nombre al socket
    socketTCP.listen() #numero de conexiones simultaneas
    conn, addr = socketTCP.accept() #aceptar conexion
    
    with conn: #conectado
        print('Se ha conectado un cliente con datos:', addr)
        comando="Quieres usar algun comando: "
        conn.send(comando.encode('utf-8')) #enviar mensaje
        data1 = conn.recv(BUFFER_SIZE) #recibir mensaje
        if(data1.decode('utf-8')=="no"): #si no quiere usar comandos
            while True: 
                data = conn.recv(BUFFER_SIZE) #recibir mensaje
                if(data.decode('utf-8')=="exit"): #si el mensaje es exit
                    print("Conexion terminada") #terminar conexion
                    socketTCP.close() #cerrar socket
                if not data: #si no hay datos
                    break #terminar conexion
                if(data.decode('utf-8')!="exit"): #si el mensaje no es exit
                    print("El cliente dice:",data.decode('utf-8')) #imprimir mensaje
                conn.send(data) #enviar mensaje
        if(data1.decode('utf-8')=="si"): #si quiere usar comandos
                archivo=conn.recv(BUFFER_SIZE) #recibir mensaje
                print("Quieres descargar el archivo: ",archivo.decode('utf-8')) #imprimir mensaje
                archivo=archivo.decode('utf-8') #convertir a string
                f = open(archivo, "rb") #abrir archivo
                tamano=os.path.getsize(archivo) #obtener tamaño del archivo
                if(f):
                    print("El archivo ",archivo," existe, vamos a enviarlo")
                    l = f.read(BUFFER_SIZE)
                    while (l):
                        conn.sendall(l)
                        l = f.read(BUFFER_SIZE)
                    print("Archivo enviado con exito de ",tamano," bytes")
                    f.close()

客户端代码

import socket

host=socket.gethostname()
port=12345
BUFFER_SIZE=1024
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socketTCP:
    socketTCP.connect((host,port))
    data = socketTCP.recv(BUFFER_SIZE)
    print(data.decode('utf-8'))
    comando=input()
    socketTCP.send(comando.encode('utf-8'))
    if(comando=="no"):
        while(data.decode('utf-8')!="exit"):
            print("Ingresa el mensaje a enviar: ")
            MSG=input()
            socketTCP.send(MSG.encode('utf-8'))
            data = socketTCP.recv(BUFFER_SIZE)
    if(comando=="si"):
            print("Quieres descargar algo, ingresa el nombre")
            archivo=input()
            socketTCP.send(archivo.encode('utf-8'))
            archivo2="Copia-"+archivo
            f = open(archivo2, "wb")
            l = socketTCP.recv(BUFFER_SIZE)
            while (l):
                f.write(l)
                print("Recibiendo archivo... con caracteres como: ",l.hex())
                l = socketTCP.recv(BUFFER_SIZE)
            print("Archivo recibido con exito")
            f.close()

问题修复步骤

1. 修正端口不匹配问题

服务器绑定的端口是7000,但客户端连接的端口是12345,两端端口必须完全一致。修改客户端的端口为7000,或者服务器端口改为12345,确保两者统一。

2. 让服务器监听所有网卡

当前服务器用socket.gethostbyname(socket.gethostname())获取本地地址,在Windows环境下可能仅绑定到localhost或非局域网网卡,导致其他机器无法访问。修改服务器的host配置:

host = "0.0.0.0"  # 替换原host赋值,监听所有可用网卡
port = 7000

3. 客户端指定服务器的局域网IP

客户端使用socket.gethostname()只能获取本地主机名,无法解析到服务器的局域网地址。手动替换为服务器的IPv4地址(可在服务器上通过ipconfig命令查看):

host = "192.168.x.x"  # 替换为服务器实际的局域网IP
port = 7000  # 和服务器端口保持一致

4. 验证网络连通性

  • 在客户端机器执行ping 服务器IP,确认两台机器能互相通信。如果ping不通,检查是否在同一子网、WiFi是否正常。
  • 确保两台机器的防火墙已关闭,或已添加Python程序的网络访问权限。

内容的提问来源于stack exchange,提问作者Miguel Ángel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 14:25:24