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

Python3 Socket跨机器文件传输遇WinError10061:目标主动拒绝连接

Python Socket跨机器文件传输出现ConnectionRefusedError: [WinError 10061]

我看了你的代码和问题描述,同一台机器运行正常但跨机器连接被拒绝,这个问题大概率是网络绑定、地址配置或者防火墙拦截导致的,下面给你一步步的解决方法:

1. 修正服务器的绑定地址

你的服务器代码里把host设为127.0.0.1(本地回环地址),这个地址只能接受本机发起的连接,其他机器根本连不上。你需要把服务器绑定到能对外提供服务的地址:

  • 最简单的方式是改成0.0.0.0,这样服务器会监听所有可用的网络接口,允许局域网内的其他机器连接:
    host = "0.0.0.0"  # 替换原来的"127.0.0.1"
    
  • 或者你可以绑定到Mac的实际局域网IP(比如192.168.1.100),可以在Mac终端用ipconfig getifaddr en0(无线网卡)或者ifconfig命令查看你的局域网IP。

2. 修正客户端的连接地址

客户端代码里的host还是127.0.0.1,这是PC自己的本地地址,你得改成Mac服务器的实际局域网IP才能连接到目标机器:

host = "192.168.1.100"  # 替换成你的Mac的局域网IP

3. 检查防火墙设置

跨机器连接最容易被防火墙拦截,两边都要检查:

  • Mac端:打开「系统设置」→「网络」→「防火墙」,确保允许你的Python程序(或者直接放行60000端口)接收外部连接。
  • PC端:打开Windows Defender防火墙,添加规则允许Python程序(或者60000端口)发起外部连接,也可以临时关闭防火墙测试(测试完记得重新打开)。

4. 先确认网络连通性

在PC的命令提示符里ping一下Mac的局域网IP,如果ping不通,说明两台机器不在同一个局域网或者网络本身有问题,先解决这个基础问题:

ping 192.168.1.100  # 替换成你的Mac的IP

修正后的完整代码示例

修改后的服务器代码:

# server.py
import socket  # Import socket module

port = 60000  # Reserve a port for your service.
s = socket.socket()  # Create a socket object
host = "0.0.0.0"  # 绑定到所有网络接口
s.bind((host, port))  # Bind to the port
s.listen(4)  # Now wait for client connection.

print('Server listening....')
while True:
    conn, addr = s.accept()  # Establish connection with client.
    print('Got connection from', addr)
    filename='send.rtf'
    print('File Assigned')
    f = open(filename,'rb')
    print('File Opened')
    l = f.read(1024)
    print('Reading')
    while (l):
        conn.send(l)
        print('Sent ',repr(l))
        l = f.read(1024)
        print('Reading')
    f.close()
    print('Done sending')
    conn.close()

修改后的客户端代码(替换Mac的IP):

# client.py
import socket  # Import socket module

s = socket.socket()  # Create a socket object
host = "192.168.1.100"  # 替换成你的Mac的局域网IP
port = 60000  # Reserve a port for your service.

s.connect((host, port))
with open('received', 'wb') as f:  # 修正了原代码的拼写错误:recieved → received
    print('file opened')
    while True:
        print('receiving data...')
        data = s.recv(1024)
        print('data=%s', (data))
        if not data:
            break
        # write data to a file
        f.write(data)
f.close()
print('Successfully got the file')
s.close()
print('Connection closed')

另外提一句:原客户端代码里的文件名recieved是拼写错误,我帮你改成了received,避免后续找文件时困惑~

内容的提问来源于stack exchange,提问作者gman1230321

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:15:02