The socket Module

The socket module implements an interface to the socket communication layer. You can create both client and server sockets using this module.

Let’s start with a client example. The client in Example 7-1 connects to a time protocol server, reads the 4-byte response, and converts it to a time value.

Example 7-1. Using the socket Module to Implement a Time Client

File: socket-example-1.py

import socket
import struct, time

# server
HOST = "www.python.org"
PORT = 37

# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00

# connect to server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

# read 4 bytes, and convert to time value
t = s.recv(4)
t = struct.unpack("!I", t)[0]
t = int(t - TIME1970)

s.close()

# print results
print "server time is", time.ctime(t)
print "local clock is", int(time.time()) - t, "seconds off"

server time is Sat Oct 09 16:42:36 1999
local clock is 8 seconds off

The socket factory function creates a new socket of the given type (in this case, an Internet stream socket, also known as a TCP socket). The connect method attempts to connect this socket to the given server. Once that has succeeded, the recv method is used to read data.

Creating a server socket is done in a similar fashion. But instead of connecting to a server, you bind the socket to a port on the local machine, tell it to listen for incoming connection requests, and process each request as fast as possible. ...

Get Python Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.