socket.socket creates a Python socket object for network communication. Pass an address family and socket type: socket.AF_INET supports hostname-and-port addresses, while socket.SOCK_STREAM selects TCP. The resulting object is not ready for clients until it is bound to an address. section 3.1
A basic TCP server uses the socket in this sequence:
- Create the server socket with socket.AF_INET and socket.SOCK_STREAM. section 3.1
- Set SO_REUSEADDR so the port can be reused after restarting. section 3.1
- Bind the socket, listen for clients, and accept a connection. section 3.1
Create a listening server socket
import socket server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind(('127.0.0.1', 8000)) server_socket.listen() connection, client_address = server_socket.accept() section 3.1
Listing 3.1 Starting a server and listening for a connection
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #1
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ('127.0.0.1', 8000) #2
server_socket.bind(server_address) #3
server_socket.listen()
connection, client_address = server_socket.accept() #4
print(f'I got a connection from {client_address}!')
Shows the complete server-socket setup from construction through accepting a client connection. section 3.1
