It seems you wrote a mixed code of server and client Here a simple sample of codes for socket programming the first on server side and the second on client
Server side code:
# server.py import socket import time # create a socket object serversocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() port = 9999 # bind to the port serversocket.bind((host, port)) # queue up to 5 requests serversocket.listen(5) while True: # establish a connection 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()
and now the client
# client.py import socket # create a socket object s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # get local machine name host = socket.gethostname() port = 9999 # connection to hostname on the port. s.connect((host, port)) # Receive no more than 1024 bytes tm = s.recv(1024) s.close() print("The time got from the server is %s" % tm.decode('ascii'))
The server simply remained listened for any client and when it finds out a new connection it returns current datetime and closes the client connection
()inclose()to close it. Second: you can't use closed socket again - you have to create new socket. BTW: you could use the same connection tosend()data to server and torecv()data from server - if you only change server too.