Python Websocket服务端通信的使用示例
作者:沙振宇 时间:2021-09-16 15:03:19
1、唠唠叨叨
最近又回顾了下Websocket,发现已经忘的七七八八了。于是用js写了客户端,用python写了服务端,来复习一下这方面的知识。
WebSocket 是一种标准协议,用于在客户端和服务端之间进行双向数据传输。但它跟 HTTP 没什么关系,它是基于 TCP 的一种独立实现。
以前客户端想知道服务端的处理进度,要不停地使用 Ajax 进行轮询,让浏览器隔个几秒就向服务器发一次请求,这对服务器压力较大。另外一种轮询就是采用 long poll 的方式,这就跟打电话差不多,没收到消息就一直不挂电话,也就是说,客户端发起连接后,如果没消息,就一直不返回 Response 给客户端,连接阶段一直是阻塞的。
而 WebSocket 解决了 HTTP 的这几个难题。当服务器完成协议升级后( HTTP -> WebSocket ),服务端可以主动推送信息给客户端,解决了轮询造成的同步延迟问题。由于 WebSocket 只需要一次 HTTP 握手,服务端就能一直与客户端保持通信,直到关闭连接,这样就解决了服务器需要反复解析 HTTP 协议,减少了资源的开销。
2、先看一下效果吧
2.1、效果1(一个客户端连上服务的并发送消息)
2.2、效果2(另一个客户端连上服务的并发送消息)
2.3、效果3(服务的收到客户端的全部消息并返回消息)
2.4、效果4(一个客户端掉线并不影响其它socket连接)
2.5、效果5(列取全部连接客户端对象和当前发消息的客户端对象)
3、核心代码
3.1、Python
#! -*- coding: utf-8 -*-
"""
Author: ZhenYuSha
Create Time: 2019-1-14
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()
3.2、Html(JS)
<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>
4、Github源码分享
https://github.com/ShaShiDiZhuanLan/Demo_Socket_Python
来源:https://blog.csdn.net/u014597198/article/details/103977632
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python字符串的全排列算法实例详解
Pycharm插件(Grep Console)自定义规则输出颜色日志的方法
![](https://img.aspxhome.com/file/2023/1/109951_0s.gif)
uni-app常用的几种页面跳转方式总结
页面软键盘汉字输入
asp如何在线压缩Access数据库?
详解TensorFlow在windows上安装与简单示例
![](https://img.aspxhome.com/file/2023/2/95542_0s.png)
pygame游戏之旅 计算游戏中躲过的障碍数量
![](https://img.aspxhome.com/file/2023/5/87755_0s.png)
Python 打印不带括号的元组的实现
![](https://img.aspxhome.com/file/2023/0/99260_0s.png)
初学者学习Python好还是Java好
详解python中eval函数的作用
Python下singleton模式的实现方法
python的Jenkins接口调用方式
![](https://img.aspxhome.com/file/2023/5/89195_0s.jpg)
Python 如何截取字符函数
Python中图像算术运算的示例详解
![](https://img.aspxhome.com/file/2023/4/108154_0s.png)
简介Django中内置的一些中间件
python tkinter界面居中显示的方法
Oracle学习笔记(五)
一文带你掌握Python中文词频统计
![](https://img.aspxhome.com/file/2023/0/66880_0s.png)