liveBook · Manning

Socket.socket

As explained in Python Concurrency with asyncio

socket.socket is the Python socket-module constructor that creates a socket object with specified address-family and socket-type parameters.

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

How Python Concurrency with asyncio covers it

How deep it goes
Explains address-family and socket-type parameters, then places construction within binding, listening, and accepting.
Examples
Uses a localhost server on port 8000 and demonstrates accepting a client connection.
What you can do after
Operate/configure a basic blocking TCP server socket and accept its first client connection.
How it connects
Connects socket construction with TCP, bind, listen, accept, and SO_REUSEADDR.

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.