ConnectionRefusedError: [Errno 61] Connection Refused in Python

ConnectionRefusedError: [Errno 61] Connection Refused in Python

  1. How the Error ConnectionRefusedError Occurs in Python
  2. How to Fix the ConnectionRefusedError in Python

Sometimes when designing a client-server program, you may get an error ConnectionRefusedError. This occurred when your client program could not connect to the server program for some coding issues.

This article will show how we get a ConnectionRefusedError in Python. Also, we will discuss the topic by using necessary examples and explanations to make the topic easier.

How the Error ConnectionRefusedError Occurs in Python

As we already discussed, this error mainly occurs when a client program cannot connect to the server. To understand these, let’s consider our client-server example program shared below.

Let’s look at our example code below for the server program.

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()

Please note that we set the port to 5000 on our above program. Now take a look at our client program.

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()

We intentionally make a mistake on our client program: we set the port on the client program to 5001. Now when you run the client program after the server program, you will get an error message like the one below.

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

This error occurred because the client program could not connect to the server. This error can also happen if you start the server program first.

In this situation, the client program will find no server program to connect with.

How to Fix the ConnectionRefusedError in Python

We can easily fix the above error using the exact server port, 5000. Now after updating the code, it will look like the below.

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()

After executing the client program, you will get the below output on the client side.

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

And you will see the below output on the server side.

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

Please note that you must run the server program before running the client program; otherwise, you will get the same error.

Please take note that the commands and programs discussed here are written in the Python programming language.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - Python Error

  • Python PermissionError: [WinError 5] Access Is Denied
  • Python TypeError: 'DataFrame' Object Is Not Callable
  • Python TypeError: Can't Convert 'List' Object to STR
  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10