Quiz 2

Socket Programming

529 words
3 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Socket Programming ## 🎯 Learning Objectives - Create TCP client/server sockets in Python - Implement UDP communication - Handle multiple connections with select/poll - Build a simple HTTP server - Apply socket options and timeouts * * * ## 1. TCP Socket ### 1.1 Server ### 1.2 Client * * * ## 2.

Socket Programming

🎯 Learning Objectives

  • Create TCP client/server sockets in Python
  • Implement UDP communication
  • Handle multiple connections with select/poll
  • Build a simple HTTP server
  • Apply socket options and timeouts

1. TCP Socket

1.1 Server

python
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 8080))
server.listen(5)  # backlog = 5
while True:
    client, addr = server.accept()  # Blocks until connection
    data = client.recv(1024)        # Receive up to 1024 bytes
    client.send(b"HTTP/1.1 200 OK\r\n\r\nHello!")
    client.close()

1.2 Client

python
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 8080))
client.send(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
response = client.recv(4096)
print(response.decode())
client.close()

2. UDP Socket

python
# Server
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(('127.0.0.1', 8081))
data, addr = server.recvfrom(1024)  # Returns (data, address)
server.sendto(b"Response", addr)
# Client
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b"Hello", ('127.0.0.1', 8081))
data, _ = client.recvfrom(1024)

3. Handling Multiple Connections

3.1 Using select

python
import select
server = socket.socket()
server.bind(('0.0.0.0', 8080))
server.listen(5)
read_list = [server]
while True:
    readable, _, _ = select.select(read_list, [], [])
    for s in readable:
        if s is server:
            client, addr = server.accept()
            read_list.append(client)
        else:
            data = s.recv(1024)
            if not data:
                read_list.remove(s)
                s.close()
            else:
                s.send(b"Echo: " + data)

4. Common Pitfalls

Pitfall 1: Blocking on recv

The mistake: Assuming recv returns the complete message. Correct approach: TCP is a stream protocol — recv may return partial data. Use message framing (length prefix) or delimiters.

Pitfall 2: UDP Datagram Size

The mistake: Sending UDP > 65507 bytes. Correct approach: UDP datagram max = 65535 bytes (IP) - 20 (IP header) - 8 (UDP header) = 65507. For reliable transmission over internet, keep under 1472 bytes (MTU 1500 - headers).

5. Key Concepts Reference

ConceptTCPUDP
ConnectionConnection-orientedConnectionless
ReliabilityGuaranteed deliveryBest-effort
OrderingPreservedNot preserved
Stream vs. datagramByte streamMessage boundaries preserved
OverheadHigher (headers + ACKs)Lower (minimal headers)

6. 📝 Practice Questions

Q1: Why does recv(1024) return only 200 bytes when the sender sent 2000?
Answer: TCP is a stream protocol — recv returns whatever data is currently available in the receive buffer (up to the requested size). The sender's 2000 bytes may arrive in multiple packets. Always loop on recv until you have the expected amount, or use message framing (send length prefix, then data). Q2: What happens if a TCP server doesn't call accept() quickly enough?
Answer: The TCP listen backlog queue fills up (default 5-128 depending on OS). Once full, new connection SYNs are either dropped (client retries) or RST (connection refused). The backlog parameter in listen() controls this queue depth. Q3: Why is UDP faster than TCP for real-time applications?
Answer: UDP has no connection setup (no 3-way handshake), no ACKs (no retransmission delay), no congestion control (no throttling), no ordering guarantees (no head-of-line blocking). For real-time applications (VoIP, gaming), losing some packets is acceptable; TCP's retransmission delay would be worse.

7. 🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.