Skip to content Skip to sidebar Skip to footer

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 conne

Solution 1:

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


Post a Comment for "Socket Server In Python Refuses To Connect"