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

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

服務(wù)的收到客戶端的全部消息并返回消息

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

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

先安裝websockets
pip install websockets
python簡(jiǎn)單聊天工具實(shí)例源碼
Python聊天工具服務(wù)端
#! -*- coding: utf-8 -*-
"""
Info: Websocket 的使用示例
"""
import asyncio
import websockets
websocket_users = set()
# 檢測(cè)客戶端權(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)
# 接收客戶端消息并處理,這里只是簡(jiǎn)單把客戶端發(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)
# 服務(wù)器端主邏輯
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簡(jiǎn)單聊天工具客戶端代碼Html+Js
<!-- Websocket 的使用示例 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>測(cè)試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("連接成功, 請(qǐng)輸入賬號(hào)和密碼");
};
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庫(kù)開發(fā)簡(jiǎn)單聊天工具實(shí)例詳細(xì),更多關(guān)于python Websocket庫(kù)開發(fā)知識(shí)請(qǐng)查看下面的相關(guān)鏈接
相關(guān)文章
Python Web框架Pylons中使用MongoDB的例子
這篇文章主要介紹了Python Web框架Pylons中使用MongoDB 的例子,大家參考使用2013-12-12
Python中使用aiohttp模擬服務(wù)器出現(xiàn)錯(cuò)誤問題及解決方法
這篇文章主要介紹了Python中使用aiohttp模擬服務(wù)器出現(xiàn)錯(cuò)誤,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
最新版 Windows10上安裝Python 3.8.5的步驟詳解
這篇文章主要介紹了最新版 Windows10上安裝Python 3.8.5的步驟詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11
Python分析特征數(shù)據(jù)類別與預(yù)處理方法速學(xué)
這篇文章主要為大家介紹了Python分析特征數(shù)據(jù)類別與預(yù)處理方法速學(xué),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
對(duì)python中array.sum(axis=?)的用法介紹
今天小編就為大家分享一篇對(duì)python中array.sum(axis=?)的用法介紹,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-06-06

