Search code examples
pythonwebsocketserverwebserversocketserver

Socket server in python refuses to connect


I am trying to create a simple web server with python using the following code. However, When I run this code, I face this error:

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

It worths mentioning that I have already tried some solutions suggesting manipulation of proxy settings in internet options. I have run the code both in the unticked and the confirmed situation of the proxy server and yet cannot resolve the issue. Could you please guide me through this ?

import sys
import socketserver
import socket

hostname = socket.gethostname()
print("This is the host name:  " + hostname)

port_number = 60000

soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.connect((hostname,port_number))

Solution

  • Standard EXAMPLE of socket connection

    SERVER & CLIENT

    run this in your IDLE

    import time
    import socket
    import threading
    HOST = 'localhost'  # Standard loopback interface address (localhost)
    PORT = 60000       # Port to listen on (non-privileged ports are > 1023)
    
    def server(HOST,PORT):
        s =  socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen(1)
    
        while True:
            conn, addr = s.accept()
            data = conn.recv(1024)
            if data:
                print(data)
                data = None
            time.sleep(1)
            print('Listening...')
    
    
    def client(HOST,PORT,message):            
        print("This is the server's hostname:  " + HOST)
    
    
        soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        soc.connect((HOST,PORT))
        soc.send(message)
        soc.close()
    
    th=threading.Thread(target = server,args = (HOST,PORT))
    th.daemon = True
    th.start()
    

    After running this, in your IDLE execute this command and see response

    >>> client(HOST,PORT,'Hello server, client sending greetings')
    This is the server's hostname:  localhost
    Hello server, client sending greetings
    >>> 
    

    If you try to do server with port 60000 but send message on different port, you will receive the same error as in your OP. That shows, that on that port is no server listening to connections