Backend Technologies

socket_001: Introduction to Sockets in Python

codeaddict 2025. 1. 30. 12:13

Sockets are the backbone of network communication. They allow programs to send and receive data over a network, enabling applications to communicate with each other. Whether you’re building a chat application, a file transfer system, or a web server, understanding sockets is essential.

 

In this tutorial, we’ll cover the basics of sockets, including what they are, how they work, and how to create a simple client-server communication using Python.


What is a Socket?

A socket is an endpoint for communication between two machines. It combines an IP address and a port number to uniquely identify a connection. Sockets can be used for various types of communication, such as TCP (Transmission Control Protocol) and UDP (User Datagram Protocol).

  • TCP: Reliable, connection-oriented communication. Data is delivered in order and without errors.
  • UDP: Unreliable, connectionless communication. Data is sent without guaranteeing delivery or order.

In this tutorial, we’ll focus on TCP sockets, as they are the most commonly used.


Basic Socket Workflow

  1. Server Side:
  • Create a socket.
  • Bind the socket to an IP address and port.
  • Listen for incoming connections.
  • Accept a connection from a client.
  • Send and receive data.
  1. Client Side:
  • Create a socket.
  • Connect to the server’s IP address and port.
  • Send and receive data.

Basic Socket Commands and Syntax

Here are the fundamental socket commands in Python:

| Command/Syntax                | Description                                                                 |
|-------------------------------|-----------------------------------------------------------------------------|
| `socket.socket()`             | Creates a new socket.                                                       |
| `socket.bind((host, port))`   | Binds the socket to a specific IP address and port.                         |
| `socket.listen()`             | Puts the socket in listening mode (for servers).                            |
| `socket.accept()`             | Accepts an incoming connection (returns a new socket and client address).   |
| `socket.connect((host, port))`| Connects to a remote socket (for clients).                              |
| `socket.send(data)`           | Sends data to the connected socket.                                         |
| `socket.recv(buffer_size)`    | Receives data from the socket (up to `buffer_size` bytes).                  |
| `socket.close()`              | Closes the socket.                                                          |

Creating a Simple TCP Server and Client

Let’s create a basic TCP server and client to demonstrate how sockets work. — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — 

Step 1: Create the TCP Server

The server will listen for incoming connections and respond to messages from the client.

Save the following code in a file named server.py:

import socket

# Create a TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to an IP address and port
server_address = ('localhost', 12345)
server_socket.bind(server_address)

# Listen for incoming connections
server_socket.listen(1)
print("Server is listening on port 12345...")

# Accept a connection
client_socket, client_address = server_socket.accept()
print(f"Connection established with {client_address}")

# Receive data from the client
data = client_socket.recv(1024).decode()
print(f"Received: {data}")

# Send a response to the client
response = "Hello from the server!"
client_socket.send(response.encode())

# Close the sockets
client_socket.close()
server_socket.close()

Step 2: Create the TCP Client

The client will connect to the server, send a message, and receive a response.

Save the following code in a file named client.py:

import socket

# Create a TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to the server
server_address = ('localhost', 12345)
client_socket.connect(server_address)

# Send data to the server
message = "Hello from the client!"
client_socket.send(message.encode())

# Receive a response from the server
data = client_socket.recv(1024).decode()
print(f"Received: {data}")

# Close the socket
client_socket.close()

Step 3: Run the Code

Follow these steps to run the server and client:

  1. Open two terminal windows:
  • One for the server.
  • One for the client.

2. Run the server:

  • In the first terminal, navigate to the directory where server.py is saved.
  • Run the server using the following command:
  • python server.py
python server.py
  • The server will start and display:
Server is listening on port 12345…

3. Run the client:

  • In the second terminal, navigate to the directory where client.py is saved.
  • Run the client using the following command
python client.py
  • The client will send a message to the server and display the server’s response:
Received: Hello from the server

4. Observe the server output:

  • After the client runs, the server terminal will display:
Connection established with ('127.0.0.1', <client_port>) Received: Hello from the client!

How It Works

  1. The server creates a socket, binds it to localhost:12345, and starts listening for connections.
  2. The client creates a socket and connects to the server at localhost:12345.
  3. The client sends a message ("Hello from the client!") to the server.
  4. The server receives the message, prints it, and sends a response ("Hello from the server!") back to the client.
  5. The client receives the response and prints it.
  6. Both the client and server close their sockets.

Output

Server Output:

Server is listening on port 12345...
Connection established with ('127.0.0.1', <client_port>)
Received: Hello from the client!

Client Output:

Received: Hello from the server!

Key Takeaways

  • Sockets are the foundation of network communication.
  • A server listens for incoming connections, while a client initiates the connection.
  • The socket module in Python provides all the tools you need to create and manage sockets.
  • Always close sockets after use to free up resources.
  •