HOWTO · Python

ConnectionRefusedError: [Errno 61] Python에서 연결 거부됨

이 자습서에서는 Python의 ConnectionRefusedError에 대해 설명합니다.

이 페이지의 내용

때때로 클라이언트-서버 프로그램을 설계할 때 ConnectionRefusedError 오류가 발생할 수 있습니다. 이것은 일부 코딩 문제로 인해 클라이언트 프로그램이 서버 프로그램에 연결할 수 없을 때 발생했습니다.

이 기사는 Python에서 ConnectionRefusedError를 얻는 방법을 보여줍니다. 또한 주제를 더 쉽게 만들기 위해 필요한 예와 설명을 사용하여 주제를 논의합니다.

Python에서 ConnectionRefusedError 오류가 발생하는 방법

이미 논의한 바와 같이 이 오류는 주로 클라이언트 프로그램이 서버에 연결할 수 없을 때 발생합니다. 이를 이해하기 위해 아래 공유된 클라이언트-서버 예제 프로그램을 살펴보겠습니다.

아래에서 서버 프로그램에 대한 예제 코드를 살펴보겠습니다.

import socket


def ServerProgram():
    host = socket.gethostname()
    port = 5000
    ServerSocket = socket.socket()
    ServerSocket.bind((host, port))
    ServerSocket.listen(2)
    conn, ClientAddress = ServerSocket.accept()
    print("Connection from: " + str(ClientAddress))
    while True:
        ClientMsg = conn.recv(1024).decode()
        if not ClientMsg:
            break
        print("from connected user: " + str(ClientMsg))
        ClientMsg = input(" -> ")
        conn.send(ClientMsg.encode())
    conn.close()


if __name__ == "__main__":
    ServerProgram()

위의 프로그램에서 포트를 5000으로 설정했습니다. 이제 클라이언트 프로그램을 살펴보십시오.

import socket


def ClientProgram():
    host = socket.gethostname()
    port = 5001
    ClientSocket = socket.socket()
    ClientSocket.connect((host, port))
    ClientMessage = input(" -> ")
    while ClientMessage.lower().strip() != "bye":
        ClientSocket.send(ClientMessage.encode())
        ServerMsg = ClientSocket.recv(1024).decode()
        print("Received from server: " + ServerMsg)
        ClientMessage = input(" -> ")
    ClientSocket.close()


if __name__ == "__main__":
    ClientProgram()

우리는 클라이언트 프로그램에서 의도적으로 실수를 합니다. 클라이언트 프로그램의 포트를 5001로 설정했습니다. 이제 서버 프로그램 다음에 클라이언트 프로그램을 실행하면 아래와 같은 오류 메시지가 나타납니다.

Traceback (most recent call last):
  File "F:\Python\client.py", line 25, in <module>
    ClientProgram()
  File "F:\Python\client.py", line 9, in ClientProgram
    ClientSocket.connect((host, port))  # connect to the server
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

이 오류는 클라이언트 프로그램이 서버에 연결할 수 없기 때문에 발생했습니다. 이 오류는 서버 프로그램을 먼저 시작한 경우에도 발생할 수 있습니다.

이 상황에서 클라이언트 프로그램은 연결할 서버 프로그램을 찾지 못합니다.

Python에서 ConnectionRefusedError를 수정하는 방법

정확한 서버 포트 5000을 사용하여 위의 오류를 쉽게 수정할 수 있습니다. 이제 코드를 업데이트하면 아래와 같이 표시됩니다.

import socket


def ClientProgram():
    host = socket.gethostname()
    port = 5000  # We fixed here.
    ClientSocket = socket.socket()
    ClientSocket.connect((host, port))
    ClientMessage = input(" -> ")
    while ClientMessage.lower().strip() != "bye":
        ClientSocket.send(ClientMessage.encode())
        ServerMsg = ClientSocket.recv(1024).decode()
        print("Received from server: " + ServerMsg)
        ClientMessage = input(" -> ")
    ClientSocket.close()


if __name__ == "__main__":
    ClientProgram()

클라이언트 프로그램을 실행하면 클라이언트 측에서 아래와 같은 출력을 얻을 수 있습니다.

 -> Hi Server
Received from server: Hi Client
 -> This is a message from the client
Received from server: This is a message from the server

그러면 서버 측에 아래와 같은 출력이 표시됩니다.

Connection from: ('192.168.0.159', 11418)
from connected user: Hi Server
 -> Hi Client
from connected user: This is a message from the client
 -> This is a message from the server

클라이언트 프로그램을 실행하기 전에 서버 프로그램을 실행해야 합니다. 그렇지 않으면 동일한 오류가 발생합니다.

여기에서 설명하는 명령과 프로그램은 Python 프로그래밍 언어로 작성되었습니다.