簡體   English   中英

Python中的套接字編程引發錯誤socket.error:<[Errno 10060]連接嘗試失敗

[英]Socket Programming in Python raising error socket.error:< [Errno 10060] A connection attempt failed

我是套接字編程的新手。 我已經實現了用於通過Internet傳輸文件的客戶端和服務器腳本。 這兩個腳本都在局域網計算機上工作。 我試圖將局域網中的文件從1MB交換到1GB,腳本運行良好。

但是,當我同時使用兩個腳本在不同的網絡上工作時,則意味着Internet。 沒用 我已經檢查了兩個系統的防火牆規則。 允許使用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分配的信息 (Google是您的朋友)。 通常,公共IP地址將由您的ISP分配(由於它們是稀缺資源,因此有時需要額外付費)。

感謝@jasonharper在評論中指出公共IP與私有IP問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM