在使用文件共享程序时,当尝试用 Ubuntu 电脑作为服务器,与 Windows 电脑作为客户端建立连接时,出现了 “error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.” 的错误提示。同时在服务器代码中设置了回送地址(host = “”)作为监听地址,并指定了端口号(port = 9988),但是当在 Ubuntu 电脑上运行服务器代码时,客户端无法连接到服务器。
- 解决方案
为了解决此问题,需要在 Ubuntu 电脑上正确配置防火墙规则,允许用于文件共享程序的端口。
以下是具体步骤:
sudo ufw allow 9988/tcp
这条命令将允许 TCP 端口 9988 的传入连接,即允许客户端连接到服务器。
执行完上述命令后,尝试再次运行服务器代码,然后在 Windows 电脑上运行客户端代码,此时应该可以正常建立连接并传输文件。
以下是使用 Python 构建的文件共享程序的服务器和客户端代码示例:
# 服务器端代码
import socket
import os.path
host = "" # 回送地址
port = 9988 # 端口号
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(5)
while True:
new_socket, (h, p) = sock.accept()
print("Client connected with IP address: " + h)
f = new_socket.recv(1024)
print(h + " asking for " + f)
if os.path.isfile(f) and os.access(f, os.R_OK):
temp = open(f, "rb")
size = os.path.getsize(f)
var = "y " + str(size)
new_socket.send(var)
ch = new_socket.recv(1024)
if ch == "y":
new_socket.send(temp.read())
print(f + " sent successfully to " + h)
temp.close()
new_socket.close()
else:
new_socket.send("n")
new_socket.close()
sock.close()
# 客户端代码
import socket
host = "192.168.1.101" # 服务器的 IP 地址
port = 9988 # 端口号
while True:
soc = socket.socket()
soc.connect((host, port))
f = input("Enter the name of the file you wish to download: ")
soc.send(f)
msg = soc.recv(1024)
if msg[0] == "y":
print("The file exists, total size: " + msg[2:])
ch = input("Download? (y/n): ")
if ch == "y" or ch == "Y":
fo = open("new_" + f, "wb")
soc.send("y")
rcv = soc.recv(1024)
fo.write(rcv)
rcv = soc.recv(1024)
while rcv:
fo.write(rcv)
rcv = soc.recv(1024)
print("File download complete.")
fo.close()
else:
print("No file with this name found on the server.")
ch = input("Want to continue? (y/n): ")
if ch == "n" or ch == "N":
break
soc.close()
通过在 Ubuntu 电脑上允许端口 9988 的传入连接,即可解决 “error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.” 的错误提示,并实现 Ubuntu 电脑作为服务器与 Windows 电脑作为客户端的文件共享。