Back to Transport Layer
Socket Programming
Learn network programming with sockets, client-server communication, and protocol implementation.
Socket Programming Concepts
Socket
Endpoint for communication between processes
Types:
- • Stream Socket (TCP)
- • Datagram Socket (UDP)
- • Raw Socket
Key Characteristics:
- • IP address + Port number
- • Bidirectional communication
- • Network abstraction
Client-Server Model
Communication pattern with server listening and client connecting
Types:
- • One-to-One
- • One-to-Many
- • Many-to-One
Key Characteristics:
- • Server binds to port
- • Client connects to server
- • Request-response pattern
TCP Socket
Connection-oriented, reliable stream socket
Types:
- • Blocking I/O
- • Non-blocking I/O
- • Multiplexed I/O
Key Characteristics:
- • Connection establishment
- • Reliable delivery
- • Flow control
UDP Socket
Connectionless, unreliable datagram socket
Types:
- • Unicast
- • Multicast
- • Broadcast
Key Characteristics:
- • No connection setup
- • Fast transmission
- • No delivery guarantee
Socket API Functions
socket()
Create a new socket
Parameters:
- • domain (AF_INET, AF_INET6)
- • type (SOCK_STREAM, SOCK_DGRAM)
- • protocol
Usage:
Creates endpoint for communication
bind()
Bind socket to address
Parameters:
- • socket descriptor
- • address structure
- • address length
Usage:
Associates socket with local address and port
listen()
Listen for connections
Parameters:
- • socket descriptor
- • backlog queue size
Usage:
Marks socket as passive, ready to accept connections
accept()
Accept incoming connection
Parameters:
- • socket descriptor
- • client address
- • address length
Usage:
Blocks until client connects, returns new socket
connect()
Connect to remote socket
Parameters:
- • socket descriptor
- • server address
- • address length
Usage:
Establishes connection to server
send()/recv()
Send/receive data
Parameters:
- • socket descriptor
- • buffer
- • length
- • flags
Usage:
Transfer data over established connection
Socket Communication Simulator
disconnected
Communication Log
No communication yet
Code Examples
Server Code
import socket
import threading
def handle_client(client_socket, address):
print(f"Connection from {address}")
while True:
try:
message = client_socket.recv(1024).decode('utf-8')
if not message:
break
print(f"Received: {message}")
# Echo the message back
client_socket.send(f"Echo: {message}".encode('utf-8'))
except Exception as e:
print(f"Error: {e}")
break
client_socket.close()
def start_server():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('localhost', 8080))
server.listen(5)
print("Server listening on port 8080...")
while True:
client_socket, address = server.accept()
client_thread = threading.Thread(
target=handle_client,
args=(client_socket, address)
)
client_thread.start()
if __name__ == "__main__":
start_server()Client Code
import socket
def start_client():
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect(('localhost', 8080))
print("Connected to server")
while True:
message = input("Enter message (or 'quit' to exit): ")
if message.lower() == 'quit':
break
client.send(message.encode('utf-8'))
response = client.recv(1024).decode('utf-8')
print(f"Server response: {response}")
except Exception as e:
print(f"Error: {e}")
finally:
client.close()
if __name__ == "__main__":
start_client()