Server refusing client connection (Python Sockets)

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:

  1. 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.
  2. 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.

From what I can see, I think you’ve neglected to encode.

Here’s the two scripts that I’ve used before as a simple client/server ‘chat’ connection:

# Name:        tcp_server

import socket
tcp1 = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
tcp_ip = ""         #Any interface
port = 9000        #Arbitrary non-privileged port
buffer_size = 1024
msg = ("Connected...")
tcp1.bind ((tcp_ip , port))
tcp1.listen(1)
con, addr = tcp1.accept()
print ("TCP Connection from: ", addr)

while True:
	data = con.recv(buffer_size).decode('utf-8')
	if not data:
		break
	print ("Data received: " + data)
	print ("Sending response: "  + data)
	con.send (data.encode('utf-8'))
tcp1.close()
# Name:        tcp_client

import socket
tcp1 = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
tcp_ip = "192.168.0.2"
port = 9000
buffer_size = 1024
msg = ("Client test.")


tcp1.connect((tcp_ip , port))
print ("Sending message: " + msg)
tcp1.send(msg.encode('utf8'))

data = tcp1.recv(buffer_size).decode('utf-8')

print ("Data reveived: " +  data)

Thank you!

I see that when you bound the listener to the port and tcp_ip, tcp_ip was an empty string.

The solution was as easy as getting rid of “127.0.0.1” and replacing it with “”.

It was my mistake blindly trusting non-standard uses of this module via an article online. Is there a reason this didn’t work even though I opened the port on the localhost? Is this the decoding you mentioned?

No worries.

This is kind of on the edge of my understanding, but there are OPs here that will know for sure.

Looking again, it could be that your code line s.sendall(b"Hello, world") is doing said coding, but I stand to be corrected.

I think that the reason that ‘localhost’ won’t work (again I stand to be corrected) is that the network can’t route that.

The scripts that I posted, I can’t take credit for the coding, but I did manage to use them as a connection test and from there code up a simple chat section. The code I used has long gone, but the scripts here were still in my notes.