Eli Kerrison-Male Eli Kerrison-Male - 13 days ago 6
Python Question

Connecting with socket gives ConnectionRefusedError

I have just begun to learn the Socket library in Python. I am following a tutorial, but in one of the very first examples I get an error when I try to run it.

import socket # Import socket module

s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.

s.connect((host, port))
print(s.recv(1024))
s.close


At first I wrote it in by hand, but, after getting the error message after several reviews I directly copied the text into Python and ran it. But for some reason I still get this Error.

Traceback (most recent call last):
File "C:\Users\elikerr\Documents\socketFirstServer.py", line 7, in <module>
s.connect((host, port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it


Can someone please elaborate on what is going wrong.
This is the tutorial I'm following.
I have checked some of the answers on Stack Exchange, but none of them seem to answer my question, or, if they do I do not know enough about Sockets to know what I am looking for.

Answer

Since you only posted the client code I will assume you went ahead to writing the client before setting up the server.

You need to put the following code in file (server.py) and run it.

#!/usr/bin/python           # This is server.py file

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

Now verify the server is running like so:

C:\Users\pp9x2>netstat -an | findstr 12345
TCP    192.168.56.1:12345     0.0.0.0:0              LISTENING

Now use the exact code you posted and everything should just work.