Python套接字中的ConnectionRefusedError

时间:2016-08-04 12:39:04

标签: python sockets

我有一些充当套接字服务器的代码:

import threading
import socketserver


class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        ip, port = self.client_address
        print("{}:{} connected.".format(ip, port))
        try:
            while True:
                data = str(self.request.recv(1024), 'ascii')
                print("{}:{} - {}".format(ip, port, data))
                cur_thread = threading.current_thread()
                response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
                self.request.sendall(response)
        except ConnectionError:
            print("{}:{} lost connection.".format(ip, port))


class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass


def make_server() -> ThreadedTCPServer:
    host, port = "127.0.0.1", 9191

    server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler, False)
    server.allow_reuse_address = True
    server.server_bind()

    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(target=server.serve_forever)
    # Exit the server thread when the main thread terminates
    server_thread.daemon = True
    server_thread.start()
    print("Server started.")
    return server

我试图连接到终端中的服务器:

>>> from socket import socket
>>> s = socket()
>>> s.connect("127.0.0.1", 9191)
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

这是什么原因?

注意:此代码是从另一个python文件导入并运行的 - 运行代码时会打印"Server started."

0 个答案:

没有答案