概述
在使用python+websocket部署socket服務,前端使用小程序來連接,過程中存在以下可能出現的問題:
1,代碼里socket端口問題2,服務器配置問題(域名解析?Nginx配置是否正確處理了WebSocket升級頭?)3,小程序端口配置錯誤(是否是443:wss://example.com:443)
1,代碼里socket端口問題
代碼里端口設置為:8765。特別要留意端口是否在安全組里添加入站規則,在服務器面板中添加:
# coding: utf-8
import asyncio
import json
import logging
import websockets
from datetime import datetime
from threading import Thread
import time# 全局變量存儲所有連接的客戶端
connected_clients = {}async def handle_message(websocket, message):"""處理客戶端消息"""try:data = json.loads(message)action = data.get("action")if action == "login":# 用戶登錄user_id = data["user_id"]connected_clients[user_id] = websocketawait broadcast_system_message(f"用戶 {user_id} 上線了")print(f"用戶 {user_id} 已連接")elif action == "chat":# 聊天消息sender = data["user_id"]content = data["content"]target = data.get("target")if target: # 私聊await send_private_message(sender, target, content)else: # 群發await broadcast_message(sender, content)except Exception as e:print(f"消息處理錯誤: {e}")async def send_private_message(sender, target, content):"""發送私聊消息"""if target in connected_clients:message = {"type": "private","from": sender,"content": content,"time": datetime.now().strftime("%H:%M:%S")}await connected_clients[target].send(json.dumps(message))print(f"私聊消息: {sender} -> {target}: {content}")async def broadcast_message(sender, content):"""廣播消息給所有用戶"""message = {"type": "public","from": sender,"content": content,"time": datetime.now().strftime("%H:%M:%S")}for user_id, client in connected_clients.items():if client.open:await client.send(json.dumps(message))print(f"廣播消息: {sender}: {content}")async def broadcast_system_message(content):"""發送系統通知"""message = {"type": "system","content": content,"time": datetime.now().strftime("%H:%M:%S")}for user_id, client in connected_clients.items():if client.open:await client.send(json.dumps(message))async def handle_connection(websocket, path):"""處理新連接"""user_id = Nonetry:async for message in websocket:await handle_message(websocket, message)except websockets.exceptions.ConnectionClosed:passfinally:if user_id in connected_clients:del connected_clients[user_id]await broadcast_system_message(f"用戶 {user_id} 下線了")print(f"用戶 {user_id} 已斷開")async def health_check():"""心跳檢測(每30秒清理死連接)"""while True:await asyncio.sleep(30)dead_clients = [user_id for user_id, client in connected_clients.items()if not client.open]for user_id in dead_clients:del connected_clients[user_id]async def main():startup_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")print(f"【服務啟動】Chat Server 啟動時間: {startup_time}")# 啟動心跳檢測asyncio.create_task(health_check())# 啟動WebSocket服務器server = await websockets.serve(handle_connection,"0.0.0.0", # 監聽所有IP8765, # 端口ping_interval=None # 禁用自動ping(手動實現心跳))print("聊天服務器已啟動,等待連接...")await server.wait_closed()if __name__ == "__main__":asyncio.run(main())
2,服務器配置問題
①直接訪問地址(chat.y***.cn),發現不能訪問,首先考慮域名解析問題,添加域名解析:
②項目使用Nginx反向代理,檢查Nginx配置是否正確處理了WebSocket升級頭,查看網站配置,添加內容:
location / {proxy_pass http://localhost:8765;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}
3,小程序端口配置錯誤(是否是443:wss://example.com:443)
這個容易犯的低級錯誤,端口直接填寫了8765。?
4,前端測試代碼
wx.connectSocket({url: 'wss://chat.*****.cn:443',success: () => console.log('連接成功'),fail: (err) => console.error('連接失敗', err)})
輸出:連接成功