Socket Programming Example

The socket module

  • Provides access to low-level network programming functions.
  • Example: A server that returns the current time
     # Time server program
     from socket import *
     import time
     
     s = socket(AF_INET, SOCK_STREAM)    # Create TCP socket
     s.bind(("",8888))                   # Bind to port 8888
     s.listen(5)                         # Start listening
     
     while 1:
         client,addr = s.accept()        # Wait for a connection
         print "Got a connection from ", addr  
         client.send(time.ctime(time.time()))  # Send time back
         client.close()

Notes:

  • Socket first opened by server is not the same one used to exchange data.
  • Instead, the accept() function returns a new socket for this ('client' above).
  • listen() specifies max number of pending connections.
<<< O'Reilly OSCON 2000, Advanced Python Programming, Slide 86
July 17, 2000, beazley@cs.uchicago.edu
>>>