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()
# 檢測客戶端權限,用戶名密碼通過才能退出循環(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ā)簡單聊天工具實例詳細,更多關于python Websocket庫開發(fā)知識請查看下面的相關鏈接
相關文章
Python Web框架Pylons中使用MongoDB的例子
這篇文章主要介紹了Python Web框架Pylons中使用MongoDB 的例子,大家參考使用2013-12-12
Python中使用aiohttp模擬服務器出現(xiàn)錯誤問題及解決方法
這篇文章主要介紹了Python中使用aiohttp模擬服務器出現(xiàn)錯誤,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
最新版 Windows10上安裝Python 3.8.5的步驟詳解
這篇文章主要介紹了最新版 Windows10上安裝Python 3.8.5的步驟詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
Python分析特征數(shù)據(jù)類別與預處理方法速學
這篇文章主要為大家介紹了Python分析特征數(shù)據(jù)類別與預處理方法速學,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02
對python中array.sum(axis=?)的用法介紹
今天小編就為大家分享一篇對python中array.sum(axis=?)的用法介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06

