今天需要一个python实现websocket的demo,我的天,网上全是大段大段的代码,给的还都不全,我只想要个demo,五六行代码这种,真的是,好在后来找到了,转载一下:https://blog.csdn.net/qq_41841569/article/details/83657388
安装websockets第三发库
pip install websockets
pip install asyncio
实现websocket服务端服务
import asyncio
import websockets
@asyncio.coroutine
def echo(websocket, path):
message = yield from websocket.recv()
print('recv', message)
server_data = "收到服务端的数据"
yield from websocket.send(server_data)
start_server = websockets.serve(echo, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
实现websocket客户端服务
编写一个index.js文件,具体代码如下:
var ws = new WebSocket("ws://localhost:8765/echo")
//建立web socket 连接成功触发事件
ws.onopen = function () {
ws.send("客户端发送的数据")
console.log("数据发送中....")
};
//接收 web socket 服务端数据时触发事件
ws.onmessage = function (evt) {
var received_msg = evt.data
console.log(received_msg)
};
//断开web socket 连接成功触发事件
ws.onclose = function () {
console.log("连接已断开")
};
编写一个index.html文件,引入上面编写的js文件,来测试一下websocket的功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>websocket</title>
</head>
<body>
<script src="./index.js"></script>
</body>
</html>
在浏览器打开index.html文件,打开调试窗口,刷新页面。可以看到websocket客户端与服务端各自输出的日志。
服务端日志: