Einführung in die Socket-API
Erkunden Sie die Kernkonzepte der Socket-Programmierung, einschließlich Socket-Typen, Adressen und gängiger API-Aufrufe.
Einführung in die Socket-API ist eine kostenlose Linux Networking & TCP/IP for Developers-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Linux Networking & TCP/IP for Developers-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Linux Networking & TCP/IP for Developers-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
What are Network Sockets?
Welcome to socket programming! A socket is a crucial concept in network communication. Think of it as one endpoint of a two-way communication link between two programs running on the network.
It's like a phone jack on a wall. You plug a phone into it to connect to the phone network. Similarly, programs use sockets to connect and talk over a computer network.
Python's Socket Module
Python makes socket programming accessible through its built-in socket module. This module provides all the necessary functions and classes to create and manage sockets.
You'll typically import it at the beginning of your script. Let's see how to get started:
import socket
# Now you can use socket functions!Socket Address Families
Before creating a socket, we need to specify its address family. This determines the type of addresses the socket can work with.
socket.AF_INET: Used for IPv4 addresses (e.g.,192.168.1.1). This is the most common.socket.AF_INET6: Used for IPv6 addresses.socket.AF_UNIX: Used for communication between processes on the same machine.
We'll primarily use AF_INET for standard internet communication.
Socket Types: Stream vs. Datagram
Next, we choose the socket type, which defines the communication style.
socket.SOCK_STREAM: This type uses TCP (Transmission Control Protocol). It's reliable, ordered, and connection-oriented, like a phone call. Data arrives exactly as sent.socket.SOCK_DGRAM: This type uses UDP (User Datagram Protocol). It's connectionless and less reliable, like sending postcards. Data might arrive out of order or not at all.
Most common applications, especially web browsing, use SOCK_STREAM.
Creating Your First Socket
Now let's put it together and create a basic socket object. We'll specify the address family (IPv4) and the socket type (TCP stream).
This line creates an inactive socket that's ready to be configured for either client or server roles.
import socket
# Create a TCP/IP socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Socket created: {my_socket}")
# Don't forget to close sockets when done!
my_socket.close()Binding a Socket (Server Side)
For a server, the socket needs an address to listen on. This is called binding. You assign an IP address and a port number to your socket.
Clients will use this address and port to connect to your server. A port is a number that identifies a specific application or service on a host.
import socket
HOST = '127.0.0.1' # Localhost
PORT = 65432 # Port to listen on (> 1023 for non-privileged)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
print(f"Socket bound to {HOST}:{PORT}")
# The socket is now bound, but not yet listening or accepting.Listening for Connections
After binding, a server socket must listen for incoming client connections. The listen() method puts the socket into server mode.
The argument to listen() is the backlog, which is the maximum number of unaccepted connections that the system will allow before refusing new connections.
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1) # Allow 1 pending connection
print(f"Server listening on {HOST}:{PORT}")
# Now the server is ready to accept a connection.Accepting a Connection
When a client tries to connect, the server uses the accept() method. This method blocks (waits) until a client connects.
It then returns a new socket object (conn) representing the connection to the client, and the client's address (addr). All communication with the client happens via this new socket.
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
print("Waiting for a client connection...")
# This part would typically be in a loop in a real server
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
# Now 'conn' can be used to send/receive data to/from the client.Connecting to a Server (Client Side)
A client socket doesn't bind; instead, it uses the connect() method to establish a connection with a server that is listening on a specific IP address and port.
Once connected, the client can immediately start sending and receiving data. Data is always exchanged as bytes.
import socket
HOST = '127.0.0.1'
PORT = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((HOST, PORT))
print(f"Connected to server at {HOST}:{PORT}")
s.sendall(b'Hello from client!')
data = s.recv(1024) # Receive up to 1024 bytes
print(f"Received: {data.decode()}")
except ConnectionRefusedError:
print("Error: Server not running or not listening.")Sending and Receiving Data
Once a connection is established, data can be exchanged using sendall() and recv().
socket.sendall(data): Sends all of the byte-likedatato the connected socket. It keeps sending until all data is sent or an error occurs.socket.recv(bufsize): Receives data from the socket.bufsizeis the maximum number of bytes to be received at once. It returns an empty bytes object (b'') when the connection is closed.
Socket API Quick Check
Which of the following statements about Python's socket module and socket types is TRUE?
Recap: Intro to Sockets
Great job! In this lesson, you've taken your first steps into socket programming with Python. You learned:
- What a network socket is and its role in communication.
- About Python's
socketmodule. - The difference between address families (
AF_INET,AF_INET6) and socket types (SOCK_STREAMfor TCP,SOCK_DGRAMfor UDP). - The basic API calls:
socket()for creation,bind()andlisten()for servers, andconnect()for clients. - How
accept()handles incoming connections and howsendall()/recv()work.
Next, we'll dive deeper into building full TCP client-server applications!
Häufig gestellte Fragen
Ist die Lektion „Einführung in die Socket-API“ kostenlos?
Ja — der vollständige Text von „Einführung in die Socket-API“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Linux Networking & TCP/IP for Developers-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Linux Networking & TCP/IP for Developers-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Einführung in die Socket-API“?
Erkunden Sie die Kernkonzepte der Socket-Programmierung, einschließlich Socket-Typen, Adressen und gängiger API-Aufrufe. Du übst Linux Networking & TCP/IP for Developers mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Linux Networking & TCP/IP for Developers zu starten?
Keine Vorkenntnisse erforderlich. Linux Networking & TCP/IP for Developers auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „Einführung in die Socket-API“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Linux Networking & TCP/IP for Developers-Lektion Code schreiben und ausführen?
Ja. Jede Linux Networking & TCP/IP for Developers-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Einführung in die Socket-API
- TCP-Client-Server-Sockets
- UDP-Client-Server-Sockets
- Nicht blockierende Sockets und select()