您好,登錄后才能下訂單哦!
最近又回顧了下Websocket,發現已經忘的七七八八了。于是用js寫了客戶端,用python寫了服務端,來復習一下這方面的知識。
先看一下python簡單聊天工具最終效果
一個客戶端連上服務的并發送消息
另一個客戶端連上服務的并發送消息
服務的收到客戶端的全部消息并返回消息
一個客戶端掉線并不影響其它socket連接
列取全部連接客戶端對象和當前發消息的客戶端對象
pip install websockets
#! -*- coding: utf-8 -*- """ Info: Websocket 的使用示例 """ import asyncio import websockets websocket_users = set() # 檢測客戶端權限,用戶名密碼通過才能退出循環 async def check_user_permit(websocket): print("new websocket_users:", websocket) websocket_users.add(websocket) print("websocket_users list:", websocket_users) while True: recv_str = await websocket.recv() cred_dict = recv_str.split(":") if cred_dict[0] == "admin" and cred_dict[1] == "123456": response_str = "Congratulation, you have connect with server..." await websocket.send(response_str) print("Password is ok...") return True else: response_str = "Sorry, please input the username or password..." print("Password is wrong...") await websocket.send(response_str) # 接收客戶端消息并處理,這里只是簡單把客戶端發來的返回回去 async def recv_user_msg(websocket): while True: recv_text = await websocket.recv() print("recv_text:", websocket.pong, recv_text) response_text = f"Server return: {recv_text}" print("response_text:", response_text) await websocket.send(response_text) # 服務器端主邏輯 async def run(websocket, path): while True: try: await check_user_permit(websocket) await recv_user_msg(websocket) except websockets.ConnectionClosed: print("ConnectionClosed...", path) # 鏈接斷開 print("websocket_users old:", websocket_users) websocket_users.remove(websocket) print("websocket_users new:", websocket_users) break except websockets.InvalidState: print("InvalidState...") # 無效狀態 break except Exception as e: print("Exception:", e) if __name__ == '__main__': print("127.0.0.1:8181 websocket...") asyncio.get_event_loop().run_until_complete(websockets.serve(run, "127.0.0.1", 8181)) asyncio.get_event_loop().run_forever()
<!-- Websocket 的使用示例 --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>測試Socket——ws://127.0.0.1:8181</title> <script> var socket; if ("WebSocket" in window) { var ws = new WebSocket("ws://127.0.0.1:8181/test"); socket = ws; ws.onopen = function() { console.log('連接成功'); alert("連接成功, 請輸入賬號和密碼"); }; ws.onmessage = function(evt) { var received_msg = evt.data; document.getElementById("showMes").value+=received_msg+"\n"; }; ws.onclose = function() { alert("斷開了連接"); }; } else { alert("瀏覽器不支持WebSocket"); } function sendMeg(){ var message=document.getElementById("name").value+":"+document.getElementById("mes").value; document.getElementById("showMes").value+=message+"\n\n"; socket.send(message); } </script> </head> <body> <textarea rows="3" cols="30" id="showMes" ></textarea> <br/> <label>名稱</label> <input type="text" id="name"/> <br/> <label>消息</label> <input type="text" id="mes"/> <button onclick="sendMeg();">發送</button> </body> </html>
本文主要介紹了python使用Websocket庫開發簡單聊天工具實例詳細,更多關于python Websocket庫開發知識請查看下面的相關鏈接
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。