Neural Sync Active
Socket Programming
Registry Synced
Socket Programming
529 words
3 min read
Reading compass
Now · 🎯 Learning Objectives
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
pythonimport 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
pythonimport 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
pythonimport 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
| Concept | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Guaranteed delivery | Best-effort |
| Ordering | Preserved | Not preserved |
| Stream vs. datagram | Byte stream | Message boundaries preserved |
| Overhead | Higher (headers + ACKs) | Lower (minimal headers) |
6. 📝 Practice Questions
Q1: Why doesrecv(1024)return only 200 bytes when the sender sent 2000?Answer: TCP is a stream protocol —recvreturns 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 callaccept()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 inlisten()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
- Week 2 - TCP/UDP: Transport layer concepts
- Week 5 - Application Layer: HTTP over sockets
- BSCS4022 (OS): System calls, I/O Join Discord PreviousWireless NetworksNextNetwork Management