Session 3: Advanced Concepts in TCP Socket Programming
1. Recap of Sessions 1 and 2
- Session 1: Basics of socket programming and simple TCP client-server communication.
- Session 2: Introduction to UDP sockets and comparison with TCP.
2. Advanced Topics in TCP Socket Programming
- Multi-Client Communication:
* Allows a server to handle multiple clients simultaneously.
* Techniques: Threading, asynchronous I/O.
- Blocking vs. Non-Blocking Sockets:
* Blocking: Server waits for connections or data (simple but inefficient).
* Non-Blocking: Server performs multiple tasks concurrently using 'select' or async libraries.
- Error Handling:
* Manage socket errors like connection failures using try-except blocks.
- Socket Timeouts:
* Prevent indefinite waiting by setting timeouts using `[Link](seconds)`.
3. Multi-Client Server Using Threads
Server Code:
import socket
import threading
def handle_client(client_socket, client_address):
print(f"New connection from {client_address}")
client_socket.send("Welcome to the server!".encode())
while True:
try:
message = client_socket.recv(1024).decode()
if not message:
break
print(f"Received from {client_address}: {message}")
client_socket.send(f"Echo: {message}".encode())
except:
print(f"Connection with {client_address} closed.")
break
client_socket.close()
server_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 8080))
server_socket.listen(5)
print("Server listening on port 8080...")
while True:
client_socket, client_address = server_socket.accept()
client_thread = [Link](target=handle_client, args=(client_socket,
client_address))
client_thread.start()
Client Code:
import socket
client_socket = [Link](socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8080))
welcome_message = client_socket.recv(1024).decode()
print(welcome_message)
while True:
message = input("Enter message: ")
client_socket.send([Link]())
response = client_socket.recv(1024).decode()
print(f"Server: {response}")
if [Link]() == "exit":
break
client_socket.close()