WebSocket、WSS(WebSocket Secure)和SSE(Server-Sent Events)是三種常見的實時通信技術,它們的核心區別在于通信方向、協議實現、數據格式和適用場景 。以下是分維度的詳細解釋,并附帶Python示例和應用場景選擇原則。
1. 核心區別
維度 WebSocket WSS (WebSocket Secure)SSE (Server-Sent Events)通信方向 雙向通信(客戶端 ? 服務端) 雙向通信(加密版) 單向通信(服務端 → 客戶端) 協議 自定義協議(ws:// 或 wss://) 加密版(wss://) 基于HTTP協議(HTTP/1.1 長連接) 數據格式 支持文本和二進制數據 支持文本和二進制數據 僅支持純文本(UTF-8) 連接方式 需升級HTTP連接(握手) 加密版(升級HTTP連接) 直接使用HTTP長連接 自動重連 需手動實現 需手動實現 瀏覽器自動重連 跨域支持 支持(需配置CORS) 支持(需配置CORS) 不能跨域(HTTP get請求) 適用場景 實時雙向交互(如聊天、游戲) 高安全性場景(如金融交易) 單向數據推送(如新聞、日志更新)
2. 簡單類比與例子
WebSocket :像一對情侶互相發消息,隨時可以聊天、打游戲,實時性高。 例子 :在線多人游戲(玩家A打字,玩家B立刻看到)。SSE :像老師在黑板上寫新內容,學生只能被動接收,不能主動提問。 例子 :新聞網站實時更新頭條新聞。WSS :WebSocket的加密版,類似情侶在公共場合發消息時,用加密方式保護隱私。
3. Python實現示例
WebSocket(雙向通信)
import asyncio
import websocketsasync def echo ( websocket, path) : async for message in websocket: await websocket. send( f"服務端收到: { message} " ) start_server = websockets. serve( echo, "localhost" , 8765 ) asyncio. get_event_loop( ) . run_until_complete( start_server)
asyncio. get_event_loop( ) . run_forever( )
SSE(單向通信)
import asyncio
from http. server import BaseHTTPRequestHandler, HTTPServerclass SSEHandler ( BaseHTTPRequestHandler) : def do_GET ( self) : self. send_response( 200 ) self. send_header( 'Content-Type' , 'text/event-stream' ) self. send_header( 'Cache-Control' , 'no-cache' ) self. end_headers( ) while True : asyncio. run( self. serve( ) ) async def serve ( self) : await asyncio. sleep( 1 ) self. wfile. write( b"新消息\n\n" ) self. wfile. flush( ) def run_server ( ) : server = HTTPServer( ( host, port) , SSEHandler) server. serve_forever( ) if __name__ == "__main__" : run_server( )
WSS(加密WebSocket)
import asyncio
import websockets
import sslasync def wss_echo ( websocket, path) : async for message in websocket: await websocket. send( f"加密通道收到: { message} " ) ssl_context = ssl. SSLContext( ssl. PROTOCOL_TLSv1_2)
ssl_context. load_cert_chain( "server.crt" , "server.key" ) start_server = websockets. serve( wss_echo, "localhost" , 8766 , ssl= ssl_context)
asyncio. get_event_loop( ) . run_until_complete( start_server)
asyncio. get_event_loop( ) . run_forever( )
4. 應用場景選擇原則
場景 推薦技術 理由 實時雙向交互(如聊天) WebSocket 支持雙向通信,適合需要實時反饋的場景。 單向數據推送(如新聞) SSE 基于HTTP協議,實現簡單,適合服務器主動推送文本數據。 高安全性需求(如金融) WSS 加密通信,防止數據被竊聽。 跨域通信需求 WebSocket 通過配置CORS可跨域,而SSE因HTTP限制無法跨域。
5. 總結
WebSocket :適合需要雙向實時通信的場景,功能強大但復雜度較高。SSE :輕量級單向通信,適合簡單推送場景,實現簡單但不支持雙向。WSS :WebSocket的加密版本,適合對安全性要求高的場景。