Sockets

Basics

  • Sockets provide a communication endpoint between programs
  • Acts like a bidirectional pipe sending bytes
  • Can communicate within same machine or across network

Identification (IP + Port)

  • Each socket endpoint identified by (IP address, port number)
  • IP address → identifies machine
  • Port → identifies program on machine
  • BOTH required for unique identification

IP Address

  • IPv4 format: x.x.x.x (0–255 each)
  • 127.0.0.1 → localhost (same machine)
  • 0.0.0.0 → all network interfaces

Port Numbers

  • Range: 0–65535
  • Ports <1024 are reserved
    • 80 → HTTP
    • 443 → HTTPS

Client vs Server

Server

  • bind((IP, port)) → attach socket
  • listen() → wait for connections
  • accept() → accept client (returns new socket)
  • Handles incoming connections
Client
  • connect((IP, port)) → initiate connection
  • Must know server IP and port
Key Flow
  • Server starts first
  • Client connects
  • Server accepts → new socket created
  • Communication becomes bidirectional

Data Transmission

Bytes vs Strings

  • Sockets send bytes, NOT strings
  • Must convert:
    • str → bytes: .encode()
    • bytes → str: .decode()

Receiving Data

Problem

  • recv(n) does NOT guarantee full message
  • Data may arrive in chunks

Solution: Protocol

  • Define message boundaries (e.g. ‘\n’)

Correct Pattern

data = b''
while b'\n' not in data:
    data += socket.recv(1024)

Socket Methods (Core)

  • bind((host, port)) → attach socket
  • listen() → wait for clients
  • accept() → accept connection
  • connect((host, port)) → client connects
  • recv(n) → receive bytes
  • sendall(bytes) → send all data

Blocking Behavior

  • accept() blocks until connection arrives
  • recv() blocks until at least 1 byte received

Server Types

Iterative Server

while True:
    accept client
    handle client
  • Handles ONE client at a time

Concurrent Server

  • Uses threads/processes
  • Handles MULTIPLE clients simultaneously

Protocol Design

  • Must define:
    • Message format
    • Valid commands
    • Start/end markers

Example Messages

  • b’MOVE5\n’
  • b’END\n’

Templates

Server

import socket
s = socket.socket()
s.bind(('127.0.0.1', 12345))
s.listen()
conn, addr = s.accept()
conn.sendall(b'Hello\n')
conn.close()

Client

import socket
s = socket.socket()
s.connect(('127.0.0.1', 12345))
print(s.recv(1024))
s.close()