Python:[WinError 10054]远程主机强行关闭现有连接

时间:2017-05-17 19:41:16

标签: python eclipse python-3.x pydev eclipse-neon

我正在创建一个基于服务器的客户端聊天客户端,每次设置服务器和客户端时,服务器都会一直监听连接,当客户端尝试连接时,会出现此错误[WinError 10054] An existing connection was forcibly closed by the remote host,但是服务器仍然监听连接。我正在使用python版本3.6.1

脚本

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

1 个答案:

答案 0 :(得分:0)

如果您的服务器不在本地网络上,请确保端口7999已打开并在其接入点上转发。否则,路由器将丢弃数据包。如果它在您的本地网络上,仍然尝试转发。同样根据https://www.speedguide.net/port.php?port=7999端口已经被蠕虫使用,所以可能永久关闭在另一个网络上?不太可能但可能。