[Python] Python: [WinError 10054] An existing connection was forcibly closed by the remote host

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm creating a client to server based chat client and every time I setup a server and a client, the server keeps listening for a connection and when the client attempts to connect this error appears [WinError 10054] An existing connection was forcibly closed by the remote host, however the server still listens for a connection. I'm using python version 3.6.1

    Script

    import socket
    import threading

    clients = []
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    mode = input("Enter 1 for server mode and enter 2 for client mode")
    if mode == "1":

    def get_ip():
    try:
    stest = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    stest.connect(('10.255.255.255', 1))
    IP = stest.getsockname()[0]
    except:
    IP = '127.0.0.1'
    finally:
    stest.close()
    return IP
    print("IP: " + get_ip())
    s.bind((get_ip(), 7999))
    s.setblocking(0)

    print("Waiting for connection")
    while True:
    try:
    data, addr = s.recvfrom(1024)
    if data.decode() == "Quit":
    quitmsg = str(addr) + " has quit the chat."
    clients.remove(addr)
    for client in clients:
    s.sendto(quitmsg.encode("utf-8"), client)
    break
    elif data:
    print(data)
    if addr not in clients:
    clients.append(addr)
    print(clients[0])
    for client in clients:
    print(client)
    s.sendto(data, client)
    except:
    pass
    s.close()


    elif mode == "2":
    while True:
    try:
    ip = input("Enter in an ip address")
    socket.inet_aton(ip)
    except socket.error:
    print("Invalid IPv4 address")
    continue
    while True:
    try:
    port = int(input("Enter in port number"))
    except ValueError:
    print("Invalid Port Number")
    continue
    break
    addr = (ip, port)
    break
    s.connect(addr)

    def recvmsg():
    while True:
    data = s.recv(1024)
    print(data)
    if data:
    print(data.decode())

    recv = threading.Thread(name="recvmsg", target=recvmsg)
    recv.daemon = True
    recv.start()

    while True:
    string = input(">>")
    s.send(string.encode("utf-8"))
    if str(string) == "Quit":
    break

    s.close()
    print("Disconnected from chat")


    Server Waiting For connection even after client can't connect

    Client Failed to connect

    Continue reading...

Compartilhe esta Página