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

  • Googling "ConnectionRefusedError: [WinError 10061]" gives me [this](https://stackoverflow.com/questions/13773024/python-connectin-refused-10061), and [this](https://stackoverflow.com/questions/12993276/errno-10061-no-connection-could-be-made-because-the-target-machine-actively-re), and a few others. Have you taken a look at those? – Ramon Jul 06 '17 at 18:34

1 Answers1

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.

TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65