我一直在从事一个需要在服务器(托管在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上运行这些命令并获得以下输出:
根据您的描述,很明显这是连接问题。
首先,您必须检查您创建的防火墙规则是否仍然存在。如果它“太宽”并且允许非常广泛的访问,那么即使您不知道它也可能会自动将其删除。它在您的屏幕快照上,但是请确保再次检查。
If it's there select the protocol you're goint to be using (I assume it's TCP) - some protocols are always blocked by default by GCP (you can't change this) so creating a rule with "any protocol" allowed is risky. Also - put one or two target IP's (not all inside this VPC) - this is not a must but improves security of your network.
Second - make sure port 5555 you're trying to connect to is accessible from other computers. You can scan the target host with nmap -p 5554 put.server.ip.here
You can scan it from the Internet or other VM's in the same VPC network.
You should get something like this:
root@localhost:~$ nmap -p 443 192.168.1.6
Starting Nmap 7.70 ( https://nmap.org ) at 2020-06-25 17:12 UTC
Nmap scan report for 192.168.1.6
Host is up (0.00091s latency).
PORT STATE SERVICE
443/tcp open https
Nmap done: 1 IP address (1 host up) scanned in 0.04 seconds
If you see 5555/tcp filtered freeciv
this means that something blocks the port.
在服务器上运行nmap(我假设您运行的是某些版本的Linux),如果您不想安装任何非必要的软件,则可以使用它sudo netstat -tulpn | grep LISTEN
来获取开放端口列表(5555应该在列表中)。
还要确保服务器上的防火墙不会阻止此端口。您可以使用iptables
它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句