简体   繁体   中英

When I connect to vps I get an error: Connection refused

I wrote in vps- console two files, that work great (test message comes from the client and is displayed by the server script). Server.py:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
sock.bind(('localhost', 8884))

while True:
    try:
        client, addr = sock.accept()
    except KeyboardInterrupt:
        sock.close()
        break
    else:
        client.setblocking(True) 
        result = client.recv(1024)
        client.close()
        print('Message', result.decode('utf-8'))

Clien.py:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8884))
sock.send(b'Test message!')
sock.close()

But if I use Client.py from my home computer , I get an error:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('145.148.81.8', 8884)) #ConnectionRefusedError: [Errno 111] Connection refused
sock.send(b'Test message from my house!')
sock.close()

How to fix?

your server code:

sock.bind(('localhost', 8884))

means that the server is only listening for incoming connections on loopback device.

Change that localhost to 0.0.0.0 and then the server listens on all available network devices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM