Python 中的套接字编程引发错误 socket.error:< [Errno 10060] 连接尝试失败

2024-01-02

我是套接字编程新手。我已经实现了用于通过互联网传输文件的客户端和服务器脚本。这两个脚本都可以在局域网计算机上运行。我尝试将局域网中的文件从 1MB 交换到 1GB,脚本运行良好。

但是当我使用这两个脚本在不同的网络(即互联网)上工作时。它不起作用。我检查了两个系统的防火墙规则。允许使用 Python。这是代码片段。有人可以告诉我有什么问题吗?

Script -> Server.py

import os
import socket
file_path = r'C:\Users\Baby\Downloads\006.jpg'
file_size = str(os.path.getsize(file_path))
file_name = file_path.split('\\')[-1]
# print file_name.encode('UTF-8')
total = file_name+ '/'+file_size
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostbyname(socket.gethostname())
# value of host = '103.235.165.205' as this is my ip which i am using in client.py
s.bind((host,21000))
s.listen(5)

print 'Server is listening on {}:21000'.format(host)
conn,addr = s.accept()
print 'Got connection from IP :{} Host :{}'.format(addr[0],addr[1])
conn.send(total.encode())

with open(file_path,'rb') as data:
    while data:
        conn.send((data.read()))
        break
    conn.close()
print 'transfer complete'
s.close()

Script -> Client.py

import socket
s = socket.socket()
s.connect(('10.174.238.205',21000))
total = (s.recv(1024)).decode()
file_name , file_size = map(str,total.split('/'))
data = s.recv(int(file_size.decode()))
with open(file_name,'wb') as getfile:
    getfile.write(data)

服务器中的每个网络适配器都应与其自己的 IP 地址相关联。

s.bind() 命令应使用与您希望侦听连接器的网络适配器关联的 IP 或主机名。这应该是连接到客户端正在运行的网络的适配器。

此外,如果连接是在本地网络之外,则您必须使用公开可见的 IP。您可以阅读有关 IP 分配的信息here https://www.iana.org/numbers和许多其他地方(谷歌是你的朋友)。通常,公共 IP 地址将由您的 ISP 分配(有时需要额外费用,因为它们是稀缺资源。)

感谢 @jasonharper 在评论中指出公共 IP 与私有 IP 问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中的套接字编程引发错误 socket.error:< [Errno 10060] 连接尝试失败 的相关文章

随机推荐