python開發(fā)實例之python使用Websocket庫開發(fā)簡單聊天工具實例詳解(python+Websocket+JS)
最近又回顧了下Websocket,發(fā)現(xiàn)已經(jīng)忘的七七八八了。于是用js寫了客戶端,用python寫了服務端,來復習一下這方面的知識。
先看一下python簡單聊天工具最終效果
一個客戶端連上服務的并發(fā)送消息

另一個客戶端連上服務的并發(fā)送消息

服務的收到客戶端的全部消息并返回消息

一個客戶端掉線并不影響其它socket連接

列取全部連接客戶端對象和當前發(fā)消息的客戶端對象

先安裝websockets
pip install websockets
python簡單聊天工具實例源碼
Python聊天工具服務端
#! -*- coding: utf-8 -*-
"""
Info: Websocket 的使用示例
"""
import asyncio
import websockets
websocket_users = set()
# 檢測客戶端權(quán)限,用戶名密碼通過才能退出循環(huán)
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)
# 接收客戶端消息并處理,這里只是簡單把客戶端發(fā)來的返回回去
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...") # 無效狀態(tài)
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()
python簡單聊天工具客戶端代碼Html+Js
<!-- 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" style="width:300px;height:500px;"></textarea>
<br/>
<label>名稱</label>
<input type="text" id="name"/>
<br/>
<label>消息</label>
<input type="text" id="mes"/>
<button onclick="sendMeg();">發(fā)送</button>
</body>
</html>
本文主要介紹了python使用Websocket庫開發(fā)簡單聊天工具實例詳細,更多關(guān)于python Websocket庫開發(fā)知識請查看下面的相關(guān)鏈接
相關(guān)文章
python使用正則表達式(Regular Expression)方法超詳細
這篇文章主要介紹了python使用正則表達式(Regular Expression)方法超詳細,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12
Python-typing: 類型標注與支持 Any類型詳解
這篇文章主要介紹了Python-typing: 類型標注與支持 Any類型詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05

