Forums

socket connection refused, sometinmes

! usr/bin/python34

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
print('Listening...')
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
while True:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

#! usr/bin/python34
# Echo client program
import socket

HOST = '127.0.0.1'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Connecting...')
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))

Sometimes the connection works other times it fails with:

Connecting...
Traceback (most recent call last):
  File "/home/bgailer/socket_client.py", line 9, in <module>
    s.connect((HOST, PORT))
ConnectionRefusedError: [Errno 111] Connection refused

I can't see any correlation between success and failure. Failure is about 80% of the time.

If you're running these in PythonAnywhere consoles, they might be running on any one of the console servers in our cluster. I'm guessing you're running your client and server code in different consoles? If they happen to be running on the same machine, your code will work, but if they are not, it won't.

To get it to work consistently, you'll need to run both from the same console -- start a bash console, then run the server with python server.py & to start it in the background, then run the client with python client.py.

I should say -- we don't officially support arbitrary TCP/UDP servers on PythonAnywhere, only WSGI websites. So although you can get the code to run for experimentation using the instructions I just gave, you won't be able to run a server that's visible from outside the PythonAnywhere environment.

Thanks for the explanation.

Thus this means that if I have a TCP Server such WebSocket listening on a port such 11111, it won't be externally accessible ?

Running things from the console won't be externally available (you won't be able to connect to it)

But other people on the same server will be able to connect to it.

That's right. Right now, the only kind of externally-visible server you can run on PythonAnywhere is a WSGI-based one set up from the web tab. Changing things so that you can run externally-accessible WebSocket servers is a very popular request on our to-do list, though, so we're starting work towards supporting that soon. No timelines yet, however.