項目地址:https://github.com/CzaOrz/ioco/tree/master/open_source_project/web_socket_chathtml
項目環境:前端
前端:JS環境都已經配置好了,能夠直接使用python
後端:python3.X,還須要安裝pywss包(pywss低於0.0.9版本的有點問題,我臨時修復並更新到0.0.9了,其餘...):git
pip install pywss==0.0.9
咱們首先看下實際效果圖:github
首先打開兩個前端,看看效果(記得開啓後端服務哦):web
再來看看後臺:json
接下來,先來看服務端代碼:後端
server.pywebsocket
from pywss import Pyws, route, json, ConnectManager @route('/ws/chat') def ws_chat(request, data): json_data = json.loads(data) if json_data.get('start') == True: # 接收start指令 # 更新全部已創建鏈接的socket - 當前在線人數 request.conn.send_to_all({'online': ConnectManager.online()}) return {'sock_id': request.conn.name} # 返回自身惟一sock_id msg = json_data.get('msg') if msg: # 獲取聊天消息,發送給全部已創建鏈接的socket request.conn.send_to_all({'from': request.conn.name, 'msg': msg}) if __name__ == '__main__': ws = Pyws(__name__, address='127.0.0.1', port=8868) ws.serve_forever()
代碼比較簡單。主要流程就是:socket
一、用戶創建WebSocket鏈接後,再由前端發送啓動指令 JSON.stringify({start: true})
上述代碼,由後端獲取並解析,首先會更新全部已創建鏈接的socket的當前在線人數,也就是發送JSON:
{'online': ConnectManager.online()}
而後在返回當前用戶的惟一sock_id,固然也是以JSON的形式: {'sock_id': request.conn.name}
這一步,後端一共返回了兩個數據,online 和 sock_id,這些都會存儲在前端。
二、前端發送聊天數據,以 JSON.stringify({msg: this.content}) 的格式發送。
後臺獲取並解析,而後發送給每一位鏈接用戶,以JSON的形式: {'from': request.conn.name, 'msg': msg}
前端代碼(JS部分):
client.html
$(function(){ new Vue({ el: '#ws-chat', data(){ return{ sock_id: '', content: '', online: 0, messages: [], } }, mounted(){ this.ws = new WebSocket("ws://127.0.0.1:8868/ws/chat"); this.ws.onmessage = (ev) => { json_data = JSON.parse(ev.data); if (json_data.sock_id) { // 獲取惟一sock_id this.sock_id = json_data.sock_id; } else if (json_data.online) { // 更新當前在線人數 this.online = json_data.online; } else if (json_data.from) { this.messages.push(json_data); // 推送聊天消息至容器,交由Vue更新DOM $('#chat-content-list').parent().animate({ scrollTop: $('#chat-content-list').height() }, 1000); } }; this.ws.onclose = (ev) => { this.messages.push({from: 'WebSocket', msg: 'WebSocket後臺服務已關閉!'}); }; this.ws.onopen = (ev) => { this.messages.push({from: 'WebSocket', msg: '歡迎來到WebSocket聊天室!'}); this.ws.send(JSON.stringify({'start': true})); }; }, methods: { ws_send: function(){ if (this.content) { this.ws.send(JSON.stringify({msg: this.content})); this.content = ''; } }, }, }); })
代碼也比較簡單:
一、 this.ws = new WebSocket("ws://127.0.0.1:8868/ws/chat"); 創建WebSocket鏈接。注意路徑不要錯了。
this.ws.onopen 當websocket鏈接創建後,會執行且僅執行一次此函數
this.ws.onclose 當websocket鏈接斷開後,會執行且僅執行一次此函數
this.ws.onmessage 當有消息接收的時候會觸發此函數
大概就先這樣把,應該還挺清晰的了...