on
ai 주식투자
- Get link
- X
- Other Apps
Python Socket Library: A Comprehensive Guide with Examples
The Python socket library is a fundamental tool for network programming, enabling communication between different systems or processes. This guide provides a detailed explanation of the library, accompanied by practical examples to help you understand its core concepts and applications.
What are Sockets?
At their core, sockets are endpoints of a two-way communication link between two programs running on the network. They allow applications to send and receive data over a network, much like a phone line allows two people to talk. Sockets are a low-level interface, giving you fine-grained control over network communication.
Key Concepts
Creating a Socket
The first step is to create a socket object using the socket.socket() constructor:
import socket
# Create a TCP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Create a UDP socket
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-TCP (SOCK_STREAM) Example: Simple Server
This example demonstrates a basic TCP server that listens for connections and echoes back received data.
import socket
HOST = '127.0.0.1' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print(f"Listening on {HOST}:{PORT}")
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
print(f"Received and echoed: {data.decode()}")
-TCP (SOCK_STREAM) Example: Simple Client
This example demonstrates a basic TCP client that connects to the server and sends data.
import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
message = "Hello, Server!"
s.sendall(message.encode())
data = s.recv(1024)
print(f"Received: {data.decode()}")
-
UDP (SOCK_DGRAM) Example: Simple Communication
This example demonstrates a basic UDP communication between a server and a client. UDP is connectionless, so there's no connect() or accept() step.
UDP Server:
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.bind((HOST, PORT))
print(f"Listening on {HOST}:{PORT}")
while True:
data, addr = s.recvfrom(1024)
print(f"Received message from {addr}: {data.decode()}")
s.sendto(data, addr)
-
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
message = "Hello, UDP Server!"
s.sendto(message.encode(), (HOST, PORT))
data, addr = s.recvfrom(1024)
print(f"Received message from {addr}: {data.decode()}")
-
Common Socket Methods
Error Handling
Network operations can fail. It's crucial to handle potential exceptions like socket.error using try...except blocks.
Conclusion
The Python socket library provides a powerful and flexible way to build network applications. Understanding the core concepts and methods outlined in this guide will enable you to create a wide range of network-based solutions. Remember to choose the appropriate socket type (TCP or UDP) based on your application's requirements.
Comments
Post a Comment