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