Beginning Python From Novice to Professional (9)-Socket, pythonnovice
Socket
Small servers:
#!/usr/bin/env pythonimport sockets = socket.socket()host = socket.gethostname()port = 1234s.bind((host,port))s.listen(5)while True:c,addr = s.accept()print 'Got connection from',addrc.send('Thank you for connecting')c.close()
Small client:
#!/usr/bin/env pythonimport sockets = socket.socket()host = socket.gethostname()port = 1234s.connect((host,port))print s.recv(1024)
Run the client program after running the server:
Server printing:
Got connection from ('127.0.1.1', 61625)Got connection from ('127.0.1.1', 61626)Got connection from ('127.0.1.1', 61627)Got connection from ('127.0.1.1', 61628)Got connection from ('127.0.1.1', 61629)Got connection from ('127.0.1.1', 61630)Got connection from ('127.0.1.1', 61631)Got connection from ('127.0.1.1', 61632)Got connection from ('127.0.1.1', 61633)Got connection from ('127.0.1.1', 61634)Got connection from ('127.0.1.1', 61635)
Client printing:
Thank you for connecting