Wasif
Wasif

Reputation: 1

Python Sockets: ConnectionRefusedError when trying to connect to a remote server

Description:

I'm working on a Python application that needs to establish a connection to a remote server using sockets. However, I'm encountering a ConnectionRefusedError when trying to connect to the server.

Here's my code snippet:

import socket

host = 'example.com'
port = 8080

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    client_socket.connect((host, port))
except ConnectionRefusedError as e:
    print(f"Error: {e}")
finally:
    client_socket.close()

I've verified that the server is running and listening on the specified port, but the connection is still being refused. What could be the possible reasons for this error, and how can I troubleshoot and resolve it? Any insights or suggestions are appreciated.

Upvotes: 0

Views: 94

Answers (2)

ATOZ_xp
ATOZ_xp

Reputation: 1

First, your code is good but could be better. I advise you to use a context manager in python. That allows to manage descriptors like a socket, a file, etc. These descriptors must be closed at the end of the operation. Instead of using a try except finally, the statement takes care of that for us. You can find out more on this site: https://www.geeksforgeeks.org/context-manager-in-python/

The program is good and the problem can come from several sources. Check your internet connection, if you are in a university type professional network, the firewall can be very restrictive and prevent you from going through certain ports. Tried to connect via a classic port type 80 or 443 (port normally reserved for http and https protocols). Then check that the server you want to connect is working properly and the port is open and functional (which you apparently have already done), to be sure, you can create a test python server on the loopback interface of your computer. You can find out more on this site: https://realpython.com/python-sockets/

Finally I strongly recommand you to look at the various questions already open on stackoverflow about this error in python.

Upvotes: 0

Nikolas Valerkos
Nikolas Valerkos

Reputation: 1

I would first check with the port being used on the server that has the port 8080 open. Then if it is , I would check from the server that the python script is running on using telnet host and port to see if it opens up.

If I were you, I would start a rabbitmq server to handle the connections and user authentication. You can setup one easily with docker.

See: https://github.com/nvalerkos/cronio/tree/master/myrabbitmq

I hope this helps.

Upvotes: 0

Related Questions