AWS Python socket client TimeoutError: [WinError 10060] A connection attempt failed

AWS Python socket client TimeoutError: [WinError 10060] A connection attempt failed

我有一个 aws ec2 实例,我试图在其中创建一个服务器以与我的 windows 应用程序绑定,该 ser 可以正常工作,但每当我尝试从我的电脑上的客户端连接到服务器时,它都会给出以下错误:

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

Server.py

import socket 
import threading

HEADER = 64
PORT = 5050
SERVER = "0.0.0.0"
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")

    connected = True
    while connected:
        msg_length = conn.recv(HEADER).decode(FORMAT)
        if msg_length:
            msg_length = int(msg_length)
            msg = conn.recv(msg_length).decode(FORMAT)
            if msg == DISCONNECT_MESSAGE:
                connected = False

            print(f"[{addr}] {msg}")
            conn.send("Msg received".encode(FORMAT))

    conn.close()
        

def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")


print("[STARTING] server is starting...")
start()

Client.py

import socket

HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = "Public IPv4 DNS"
ADDR = (SERVER, PORT)

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

def send(msg):
    message = msg.encode(FORMAT)
    msg_length = len(message)
    send_length = str(msg_length).encode(FORMAT)
    send_length += b' ' * (HEADER - len(send_length))
    client.send(send_length)
    client.send(message)
    print(client.recv(2048).decode(FORMAT))

send("hi")

我的 windows 电脑上的客户端代码是 运行,我的 aws-ec2 实例上的服务器代码是 运行 Linux Os.

这是我的入站规则

我的客户端中有卡巴斯基防火墙 windows 但它会影响连接到服务器吗?

假设你的实例是 public 因为我猜你可以通过 ssh 进入它,你需要 add inbound rule 到实例的安全组,它允许从 0.0.0.0/0 或更好的连接到 5050,来自您的 home/work IP 地址。