Python facilitates network communication through two abstraction tiers.
The first tier utilizes fundamental Socket APIs derived from BSD standards, granting direct access to operating system interface methods. The second tier employs higher-level modules containing server-centric classes designed to streamline the development of network services.
Socket Initialization Parameters
When constructing a socket instance, specific arguments determine its behavior:
- Address Family (family): Defines the protocol suite, commonly
AF_INETorAF_UNIX. - Socket Type (type): Selects between connection-oriented transfer (
SOCK_STREAM) or datagram-based communication (SOCK_DGRAM). - Protocol (protocol): Typical set to zero for defaults unless specified otherwise.
Implementing a TCP Server
To establish a server, instantiate a socket using the standard library. Assign the service address and port by binding the socket object. Activate the listening queue, then enter a loop to accept incoming connections. Each accepted connection yields a new socket dedicated to client interaction.
import socket
# Create the main server socket
server_sock = socket.socket()
# Configure host and port
local_host = socket.gethostname()
server_port = 8899
# Bind to the address
server_sock.bind((local_host, server_port))
# Start listening for requests
server_sock.listen(3)
print(f'Server waiting on port {server_port}')
try:
while True:
# Block until a client connects
conn_client, addr_info = server_sock.accept()
print(f'Connection established with {addr_info}')
# Send welcome message
conn_client.send(b'Received successfully')
conn_client.close()
except KeyboardInterrupt:
pass
finally:
server_sock.close()
Developing a TCP Client
A client application requires connecting to an active server endpoint. Once connected, data is exchanged via input/output operations before releasing resources.
import socket
# Initialize client socket
client_conn = socket.socket()
# Target server details
target_host = socket.gethostname()
target_port = 8899
# Establish handshake with server
client_conn.connect((target_host, target_port))
try:
response = client_conn.recv(1024)
print(f'Received: {response.decode("utf-8")}')
finally:
client_conn.close()
Standard Library Protocols
The Python environment includes specialized libraries for various internet prtoocols:
| Protocol | Functionality | Default Port | Module |
|---|---|---|---|
| HTTP | Web page retrieval | 80 | http.client, urllib |
| NNTP | News article access | 119 | nntplib |
| FTP | File transmission | 20/21 | ftplib, urllib |
| SMTP | Outbound email delivery | 25 | smtplib |
| POP3 | Email inbox fetching | 110 | poplib |
| IMAP4 | Remote mailbox management | 143 | imaplib |
| Telnet | Remote command line | 23 | telnetlib |
| Gopher | Information retrieval | 70 | gopherlib |