Context:
I’m creating scripts to facilitate communication between two hosted ubuntu servers using Python’s Socket module. These two servers have a firewall allowing access to the client at port 1234. One server is acting as a client and the other the server for socket scripts I have set up. I then created a script to listen at this exposed port and accept connections. Both scripts are below. (these scripts are just for testing purposes)
# test-server.py
import socket
HOST = "127.0.0.1" # Standard loopback interface address (localhost)
PORT = 1234 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept() # What waits for a connection
with conn:
print('Connected by {addr}')
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
# test-client.py
import socket
HOST = "12.345.678.90" # Server ip address
PORT = 1234 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print(f"Received {data!r}")
Issue:
When the server is started and running I switch to the client while leaving the server running and run the client script to test the connection and I get this error:
> python3 test-client.py
Traceback (most recent call last):
File "test-client.py", line 7, in <module>
s.connect((HOST, PORT))
ConnectionRefusedError: [Errno 111] Connection refused
What I’ve tried:
- I’ve double checked the exposed port and made sure that the socket is running and listening using grep.
- Dumbed down these files to be the bare minimum of what I need.
Possible solutions:
- I believe that there may be an issue with the .bind and .connect methods. I’m not sure if I am using them incorrectly even after checking python’s official documentation and examples of how they are used.
- There could be another issue with “port forwarding” (a topic still confusing to me). Digital Ocean is the host and I’m not sure if there are others facing networking issues like this.