0

I recently started learning socket programming with python. Starting with the most basic scripts of server and client on the same computer, I wrote the following code.

Server.py

import socket
import time

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
serversocket.bind((host,port))
serversocket.listen(5)

while True:
    clientsocket, addr = serversocket.accept()
    print("Got a connection from %s" %str(addr))
    currentTime = time.ctime(time.time()) + "\r\n"
    clientsocket.send(currentTime.encode('ascii'))
    clientsocket.close()

Client.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.connect((host,port))
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" %tm.decode('ascii'))

I'm using spyder IDE. Whenever I run the client in the IPython Console, this is what I get: "ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it."

and whenever I run the Server I get an unending process.

So, what should I do to make this work?

Thank you for any help!

Credits :- http://www.bogotobogo.com/python/python_network_programming_server_client.php

1
  • Googling "ConnectionRefusedError: [WinError 10061]" gives me this, and this, and a few others. Have you taken a look at those? Commented Jul 6, 2017 at 18:34

1 Answer 1

3

Try changing socket.gethostname() to socket.gethostbyname(socket.gethostname()). gethostbyname returns the ip for the hostname. You want to setup a socket to connect to an ip, port. Alternatively, since you are running everything locally, just set your host to "127.0.0.1" directly for both the client/server.

Sign up to request clarification or add additional context in comments.

1 Comment

I would probably just advise to use 'localhost','127.0.0.1', or '0.0.0.0' ... but great answer +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.