Abhishek Dubey
Abhishek Dubey

Reputation: 1

Python Socket Programming - Server Client basic

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

Upvotes: 0

Views: 670

Answers (1)

TheoretiCAL
TheoretiCAL

Reputation: 20581

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.

Upvotes: 3

Related Questions