https://docs.python.org/3/library/socket.html#example
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
# Echo client program
import socket
HOST = '1.2.3.4' # The remote host (I change this with my box's IP)
PORT = 50007 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
注意:我使用的是实际的EC2 IP,而不是1.2.3.4
如果我在本地机器上运行客户机,而在远程机器上运行服务器(由vultr托管),它就可以工作。
但如果将服务器托管在AWS EC2实例上,则不会。
我进入了EC2实例的安全组,添加了入站+出站“自定义TCP+UDP”规则。我尝试过允许服务器使用的特定端口,以及
0-65535
.
我想不出还有什么好尝试的。