0Pricing
FastAPI Backend Development Bootcamp · บทเรียน

การสร้างแอปพลิเคชันแชทแบบเรียลไทม์

พัฒนาแอปพลิเคชันแชทแบบเรียลไทม์อย่างง่ายเพื่อสาธิตความสามารถของ WebSocket ใน FastAPI

การสร้างแอปพลิเคชันแชทแบบเรียลไทม์ เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Real-time Chat App Overview

Welcome to building your very own real-time chat application! This lesson brings together everything we've learned about WebSockets in FastAPI.

  • We'll create a FastAPI server that manages multiple chat connections.
  • Clients will connect via WebSockets to send and receive messages instantly.
  • You'll see both the server-side (FastAPI) and a simple client-side (HTML/JavaScript) implementation.

Get ready to see real-time communication in action!

Managing Chat Connections

For a chat application, our server needs to keep track of all active WebSocket connections. When a user sends a message, the server will broadcast it to everyone else.

We'll use a simple ConnectionManager class to handle adding, removing, and broadcasting messages to connected clients.

from typing import List
from fastapi import WebSocket

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def send_personal_message(self, message: str, websocket: WebSocket):
        await websocket.send_text(message)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

FastAPI WebSocket Endpoint

Now let's create the FastAPI endpoint that clients will connect to. This endpoint will use our ConnectionManager.

When a client connects, we add them. When they send a message, we broadcast it. If they disconnect, we remove them.

from fastapi import FastAPI, WebSocket, WebSocketDisconnect

# ... ConnectionManager class from previous scene ...

app = FastAPI()
manager = ConnectionManager()

@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            message = f"Client #{client_id} says: {data}"
            await manager.broadcast(message)
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client #{client_id} left the chat")

Client-Side HTML Structure

Our chat application needs a simple user interface. We'll use basic HTML for an input field to send messages and a div to display them.

This is the foundation for our client-side interaction.

<!DOCTYPE html>
<html>
    <head>
        <title>Chat App</title>
    </head>
    <body>
        <h1>FastAPI Chat</h1>
        <form action="" onsubmit="sendMessage(event)">
            <input type="text" id="messageText" autocomplete="off"/>
            <button>Send</button>
        </form>
        <ul id='messages'>
        </ul>
    </body>
</html>

Connecting with JavaScript

Now, let's add JavaScript to our HTML to connect to the FastAPI WebSocket server. We'll open a connection as soon as the page loads.

Remember to replace localhost:8000 with your server address if it's different!

<script>
    var ws = new WebSocket("ws://localhost:8000/ws/1");

    ws.onopen = function(event) {
        console.log("Connected to WebSocket server!");
    };

    ws.onclose = function(event) {
        console.log("Disconnected from WebSocket server.");
    };

    ws.onerror = function(error) {
        console.error("WebSocket Error: ", error);
    };
</script>

Sending Messages from Client

Users need to be able to type a message and send it to the server. We'll create a JavaScript function that captures the input and sends it via the WebSocket connection.

This function is called when the form is submitted.

<script>
    // ... WebSocket connection setup ...

    function sendMessage(event) {
        var input = document.getElementById("messageText");
        ws.send(input.value);
        input.value = '';
        event.preventDefault();
    }
</script>

Receiving & Displaying Messages

The core of a chat application is receiving messages and displaying them. We'll implement the ws.onmessage event handler to append new messages to our list.

<script>
    // ... WebSocket connection & sendMessage function ...

    ws.onmessage = function(event) {
        var messages = document.getElementById('messages');
        var message = document.createElement('li');
        var content = document.createTextNode(event.data);
        message.appendChild(content);
        messages.appendChild(message);
    };
</script>

Full FastAPI Chat Server

Here's the complete Python code for our FastAPI chat server. Save this as main.py and run it using uvicorn main:app --reload.

This server will listen for connections, broadcast messages, and announce user joins/leaves.

from typing import List
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse

class ConnectionManager:
    def __init__(self):
        self.active_connections: List[WebSocket] = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)

app = FastAPI()
manager = ConnectionManager()

html = """
<!DOCTYPE html>
<html>
    <head>
        <title>Chat App</title>
    </head>
    <body>
        <h1>FastAPI Chat</h1>
        <form action="" onsubmit="sendMessage(event)">
            <input type="text" id="messageText" autocomplete="off"/>
            <button>Send</button>
        </form>
        <ul id='messages'>
        </ul>
        <script>
            var ws = new WebSocket("ws://localhost:8000/ws/1"); // Client ID is 1 for this example

            ws.onopen = function(event) {
                console.log("Connected to WebSocket server!");
            };

            ws.onmessage = function(event) {
                var messages = document.getElementById('messages');
                var message = document.createElement('li');
                var content = document.createTextNode(event.data);
                message.appendChild(content);
                messages.appendChild(message);
            };

            ws.onclose = function(event) {
                console.log("Disconnected from WebSocket server.");
            };

            ws.onerror = function(error) {
                console.error("WebSocket Error: ", error);
            };

            function sendMessage(event) {
                var input = document.getElementById("messageText");
                ws.send(input.value);
                input.value = '';
                event.preventDefault();
            }
        </script>
    </body>
</html>
"""

@app.get("/")
async def get():
    return HTMLResponse(html)

@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    await manager.broadcast(f"Client #{client_id} joined the chat")
    try:
        while True:
            data = await websocket.receive_text()
            message = f"Client #{client_id} says: {data}"
            await manager.broadcast(message)
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client #{client_id} left the chat")

Quick Chat Logic Check

You've built a basic chat app! Consider the ConnectionManager's broadcast method and the FastAPI endpoint's logic.

If Client A sends a message to the server, what happens next to ensure Client B receives it?

Chat App Summary

Congratulations! You've successfully built a basic real-time chat application using FastAPI WebSockets.

  • You learned to manage multiple active WebSocket connections with a ConnectionManager.
  • You implemented a FastAPI WebSocket endpoint to handle incoming and outgoing messages.
  • You created a simple HTML/JavaScript client to connect, send, and receive chat messages.

This project demonstrates the power of WebSockets for real-time communication. From here, you can add features like user authentication, persistent chat history, and more robust UI/UX.

คำถามที่พบบ่อย

บทเรียน “การสร้างแอปพลิเคชันแชทแบบเรียลไทม์” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้างแอปพลิเคชันแชทแบบเรียลไทม์” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้างแอปพลิเคชันแชทแบบเรียลไทม์”

พัฒนาแอปพลิเคชันแชทแบบเรียลไทม์อย่างง่ายเพื่อสาธิตความสามารถของ WebSocket ใน FastAPI คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้างแอปพลิเคชันแชทแบบเรียลไทม์” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. พื้นฐานโพรโทคอล WebSocket
  2. การใช้งาน WebSockets ใน FastAPI
  3. การสร้างแอปพลิเคชันแชทแบบเรียลไทม์
  4. การขยาย WebSockets ด้วยแบ็กเพลน Pub/Sub
← กลับไปที่ FastAPI Backend Development Bootcamp