How to Fix ConnectionRefusedError: [Errno 61] Connection Refused in Python
-
How the Error
ConnectionRefusedError
Occurs in Python -
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.
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.
LinkedInRelated Article - Python Error
- Can Only Concatenate List (Not Int) to List in Python
- How to Fix Value Error Need More Than One Value to Unpack in Python
- How to Fix ValueError Arrays Must All Be the Same Length in Python
- Invalid Syntax in Python
- How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python