> For the complete documentation index, see [llms.txt](https://telecom-1.gitbook.io/telecom/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://telecom-1.gitbook.io/telecom/5.1/quickstart/projects-and-practical-skills/software-based-projects/simulated-paging-system-python-based.md).

# Simulated Paging System (Python-Based)

#### 🛠️ **Project: Simulated Paging System (Python-Based)**

We'll build a **software-based paging system** where users can send and receive short messages. This project simulates how real-world pagers work but will function entirely on your computer.

***

#### 📋 **Project Overview:**

1. **Sender Module** – Allows users to input and send messages.
2. **Receiver Module** – Displays received messages in real-time.
3. **Message Storage** – Saves and retrieves message logs using a database (SQLite).

***

#### 📦 **Tools & Libraries You'll Need:**

1. **Python** (v3.8 or newer)
2. **Flask** (for a web-based interface)
3. **SQLite** (for message storage)
4. **WebSockets** (for real-time messaging)

***

#### ✅ **Step 1: Environment Setup**

Make sure Python is installed:

```bash
python --version
```

If not installed, download it from [python.org](https://www.python.org/downloads/).

Create a project folder:

```bash
mkdir paging_system && cd paging_system
```

Set up a virtual environment (optional but recommended):

```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

Install necessary packages:

```bash
pip install flask flask-socketio
```

***

#### 📊 **Step 2: Project Structure**

We'll organize our project as follows:

```
paging_system/
├── app.py             # Main application
├── templates/
│    └── index.html    # Web interface for paging
└── messages.db        # SQLite database (auto-created)
```

***

#### 🧑‍💻 **Step 3: Create the Paging System**

Here’s the initial code setup to create a simple client-server paging system.

First, we’ll implement the **server** that listens for incoming messages and displays them.

```python
# server.py (Receiver)
import socket

HOST = '127.0.0.1'  # Localhost
PORT = 65432        # Port to listen on

# Create a server socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((HOST, PORT))
server_socket.listen()

print(f"Paging server started. Waiting for messages on {HOST}:{PORT}...")

# Accept incoming messages
conn, addr = server_socket.accept()
with conn:
    print(f"Connected to {addr}")
    while True:
        message = conn.recv(1024).decode('utf-8')
        if not message:
            break
        print(f"New Page Received: {message}")
```

Next, we’ll create the **client** that sends messages to the server.

```python
# client.py (Sender)
import socket

HOST = '127.0.0.1'  # Server IP
PORT = 65432        # Server Port

# Create a client socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((HOST, PORT))

print("Connected to the paging server.")

while True:
    message = input("Enter a message to page (type 'exit' to quit): ")
    if message.lower() == 'exit':
        break
    client_socket.sendall(message.encode('utf-8'))

client_socket.close()
```

#### How This Works:

* **Server**: Listens for incoming messages and prints them to the console.
* **Client**: Takes user input and sends it as a page to the server.

#### How to Run the Project:

1. Save the code in two separate files (`server.py` and `client.py`).
2. Open two terminal windows.
3. In the first terminal, run: `python server.py`
4. In the second terminal, run: `python client.py`
5. Start typing messages in the **client**, and they’ll appear in the **server** terminal.

<figure><img src="/files/vWPSTP2sS1CgWxUzPdAO" alt=""><figcaption></figcaption></figure>

* **Message History** 📜 → Teaches **data storage and retrieval**, similar to how real pagers log messages.
* **Timestamps** ⏰ → Helps understand **message timing and synchronization**, crucial in wireless systems.
* **Multiple Clients** 👥 → Simulates a real-world **paging network with multiple users**, similar to mobile communication.

```python
import socket
import threading
import time

# Server Code
class PagingServer:
    def __init__(self, host='127.0.0.1', port=12345):
        self.host = host
        self.port = port
        self.clients = []  # List of connected clients
        self.message_history = []  # Store message history
        
    def start(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind((self.host, self.port))
        server.listen(5)
        print(f"Paging Server started on {self.host}:{self.port}")
        
        while True:
            client_socket, addr = server.accept()
            self.clients.append(client_socket)
            print(f"New client connected: {addr}")
            threading.Thread(target=self.handle_client, args=(client_socket,)).start()
        
    def handle_client(self, client_socket):
        while True:
            try:
                message = client_socket.recv(1024).decode('utf-8')
                if not message:
                    break
                
                timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
                formatted_message = f"[{timestamp}] {message}"
                self.message_history.append(formatted_message)
                
                print(formatted_message)  # Display on server
                self.broadcast(formatted_message, client_socket)
            except:
                break
        
        client_socket.close()
        self.clients.remove(client_socket)
    
    def broadcast(self, message, sender_socket):
        for client in self.clients:
            if client != sender_socket:
                try:
                    client.send(message.encode('utf-8'))
                except:
                    self.clients.remove(client)

# Client Code
class PagingClient:
    def __init__(self, host='127.0.0.1', port=12345):
        self.host = host
        self.port = port
        
    def start(self):
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect((self.host, self.port))
        threading.Thread(target=self.receive_messages, args=(client,)).start()
        
        while True:
            message = input("Enter message: ")
            if message.lower() == 'exit':
                break
            client.send(message.encode('utf-8'))
        
        client.close()
        
    def receive_messages(self, client):
        while True:
            try:
                message = client.recv(1024).decode('utf-8')
                print("\nReceived:", message)
            except:
                break

if __name__ == "__main__":
    choice = input("Start Server (S) or Client (C)? ").strip().lower()
    
    if choice == 's':
        server = PagingServer()
        server.start()
    elif choice == 'c':
        client = PagingClient()
        client.start()

```

<figure><img src="/files/xhCutDcWhl42kIIaffTG" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://telecom-1.gitbook.io/telecom/5.1/quickstart/projects-and-practical-skills/software-based-projects/simulated-paging-system-python-based.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
