简易多人聊天系统设计方案 系统架构概述 设计一个基于Android前端和Python Django+WebSocket和JWT的聊天系统,使用JSON作为数据交换格式。
技术栈 前端: Android (Kotlin/Java)
后端: Python + Django + Django REST Framework + Channels + JWT
数据库: SQLite (开发)/PostgreSQL (生产)
通信协议: HTTP/HTTPS
数据格式: JSON
API设计
- 注册玩家 端点: POST /api/register/
请求体:
json { "username": "string", "password": "string", "email": "string" } 响应:
json { "id": "integer", "username": "string", "email": "string", "token": "string" } 2. 发送消息 端点: POST /api/messages/
请求头: Authorization: Token <user_token>
请求体:
json { "content": "string" } 响应:
json { "id": "integer", "sender": "string", "content": "string", "timestamp": "datetime" } 3. 获取所有消息 端点: GET /api/messages/
请求头: Authorization: Token <user_token>
响应:
json { "messages": [ { "id": "integer", "sender": "string", "content": "string", "timestamp": "datetime" }, // ...更多消息 ] } 后端实现 (Django) 安装依赖 bash pip install django djangorestframework django-cors-headers line-bot-sdk pip install channels channels-redis djangorestframework-simplejwt pyjwt
项目结构 chat_project/ ├── venv/ # 虛擬環境 ├── chat_project/ # 專案設定目錄 │ ├── init.py │ ├── settings.py # 專案設定 │ ├── urls.py # 主URL配置 │ ├── asgi.py # ASGI設定 │ └── wsgi.py # WSGI設定 ├── chat_app/ # 聊天應用程式 │ ├── init.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ ├── views.py │ └── migrations/ ├── manage.py # Django管理腳本 └── requirements.txt # 依賴套件列表
部署和运行 后端部署
- 安装Redis bash
sudo apt-get install redis-server
brew install redis
redis-server 2. 安装依赖: pip install -r requirements.txt
-
迁移数据库: python manage.py migrate
-
创建超级用户: python manage.py createsuperuser
5.运行服务器: python manage.py runserver 0.0.0.0:8000
Android应用配置 修改ApiClient中的BASE_URL为你的服务器实际IP地址。 Android配置 确保在AndroidManifest.xml中添加网络权限: xml
[Python] 環境準備
- 安裝 Python 首先確認系統已安裝 Python 3.8+:
bash python --version
python3 --version 如果未安裝,請到 Python官網 下載安裝。
- 安裝虛擬環境工具 bash
pip install virtualenv
pip3 install virtualenv 專案建立步驟 步驟 1: 建立專案目錄 bash mkdir chat_project cd chat_project 步驟 2: 建立虛擬環境 bash
python -m venv venv
python3 -m venv venv 步驟 3: 啟動虛擬環境 bash
venv\Scripts\activate
source venv/bin/activate 啟動後命令提示符前會顯示 (venv)。
步驟 4: 安裝必要套件 bash pip install django channels channels-redis djangorestframework djangorestframework-simplejwt django-cors-headers 步驟 5: 建立 Django 專案 bash django-admin startproject chat_project . 注意最後的點號表示在當前目錄建立專案。
步驟 6: 建立聊天應用程式 bash python manage.py startapp chat_app
測試運行 步驟 22: 啟動Redis伺服器 bash
sudo apt install redis-server
brew install redis
redis-server 步驟 23: 運行Django開發伺服器 bash python manage.py runserver 0.0.0.0:8000 步驟 24: 測試API 使用瀏覽器或Postman測試API端點:
http://localhost:8000/api/register/ - 註冊用戶
http://localhost:8000/api/login/ - 登入獲取JWT
http://localhost:8000/api/messages/ - 獲取消息列表
http://localhost:8000/admin/ - 管理後台
生產環境部署建議 步驟 25: 生產環境設定 設置 DEBUG = False
設置安全的 SECRET_KEY
配置正確的 ALLOWED_HOSTS
使用PostgreSQL數據庫
設置靜態文件服務
使用nginx + Gunicorn部署
步驟 26: 環境變數管理 建立 .env 文件:
bash DEBUG=False SECRET_KEY=你的生產環境密鑰 ALLOWED_HOSTS=yourdomain.com,localhost DATABASE_URL=postgresql://username:password@localhost:5432/chat_db
[Android] 環境準備
- 安裝 Android Studio 下載 Android Studio
按照安裝嚮導完成安裝
安裝必要的 SDK 和工具
- 檢查系統要求 Android Studio 2022.3.1 或更高版本
JDK 17 或更高版本
至少 8GB RAM
至少 10GB 硬碟空間
建立新專案 步驟 1: 開啟 Android Studio 並建立新專案 開啟 Android Studio
點擊 "New Project"
選擇 "Empty Activity" 模板
點擊 "Next"
步驟 2: 配置專案設定 plaintext Name: ChatApp Package name: com.example.chatapp Save location: 選擇你的專案目錄 Language: Kotlin Minimum SDK: API 24 (Android 7.0) 步驟 3: 等待專案建立完成 Gradle 會自動下載依賴項並建立專案結構
專案結構說明 建立完成後的專案結構:
text ChatApp/ ├── app/ │ ├── src/ │ │ ├── main/ │ │ │ ├── java/com/example/modernchatapp/ │ │ │ │ ├── data/ │ │ │ │ ├── network/ │ │ │ │ ├── ui/ │ │ │ │ ├── utils/ │ │ │ │ └── di/ │ │ │ ├── res/ │ │ │ │ ├── layout/ │ │ │ │ ├── drawable/ │ │ │ │ ├── values/ │ │ │ │ └── navigation/ │ │ │ └── AndroidManifest.xml │ │ └── test/ │ ├── build.gradle.kts │ └── proguard-rules.pro ├── gradle/ ├── build.gradle.kts └── settings.gradle.kts
步驟 4: 修改 build.gradle (Module: app) gradle plugins { id 'com.android.application' id 'org.jetbrains.kotlin.android' id 'kotlin-parcelize' }
android { namespace 'com.example.chatapp' compileSdk 34
defaultConfig {
applicationId "com.example.chatapp"
minSdk 24
targetSdk 34
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}
buildFeatures {
viewBinding true
dataBinding true
}
}
dependencies { implementation 'androidx.core:core-ktx:1.12.0' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.11.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.7.0' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0' implementation 'androidx.navigation:navigation-fragment-ktx:2.7.7' implementation 'androidx.navigation:navigation-ui-ktx:2.7.7'
// 網路請求相關
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
// WebSocket
implementation 'org.java-websocket:Java-WebSocket:1.5.4'
// JSON 處理
implementation 'com.google.code.gson:gson:2.10.1'
// Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3'
// Lifecycle
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.7.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
} 步驟 5: 同步 Gradle 點擊 "Sync Now" 按鈕下載所有依賴項
設定權限 步驟 6: 修改 AndroidManifest.xml xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.ChatApp"
android:usesCleartextTraffic="true"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.ChatApp">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LoginActivity"
android:exported="false" />
<activity
android:name=".RegisterActivity"
android:exported="false" />
<activity
android:name=".ChatActivity"
android:exported="false" />
</application>