【发布时间】:2020-06-25 05:46:16
【问题描述】:
我一直在从事一个需要在服务器(托管在 GCE 上)和多个客户端之间进行一些网络连接的项目。我创建了一个 Compute Engine 实例来运行 Python 脚本,如以下视频所示:https://www.youtube.com/watch?v=5OL7fu2R4M8。
这是我的服务器端脚本:
server = socket.gethostbyname(socket.gethostname()) # 10.128.X.XXX which is the Internal IP
print(server)
port = 5555
clients = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((server, port))
s.listen(2)
print("Waiting for connection...")
while True:
conn, addr = s.accept()
print("Connected to: ", addr)
conn.send(str.encode(f"{clients}"))
clients += 1
这是我的客户端脚本:
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "10.128.0.2"
self.port = 5555
self.addr = (self.server, self.port)
self.id = int(self.connect())
def connect(self):
self.client.connect(self.addr)
return self.client.recv(2048).decode()
network = Network()
print(f"Connected as client {network.id}")
我知道这个脚本可以工作,因为我已经用我的计算机作为服务器和 1 个客户端以及另一台计算机作为第二个客户端对其进行了测试。但是当我使用 GCE 作为服务器时,我在客户端脚本中得到了这个错误:
TimeoutError: [WinError 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
这可能是因为我使用的是内部 IP 地址而不是外部 IP 地址吗?
在此之后,我尝试更改 GCE 的防火墙设置(添加了“python-socket”),它们看起来是这样的:
但错误仍然存在...
正如 W_B 所回答的那样,我尝试在我的 VM 上运行这些命令并得到以下输出:
【问题讨论】:
标签: python sockets networking google-compute-engine firewall