python部分
import json
import websockets
import asyncio
'''
https://websockets.readthedocs.io/en/stable/
python websocket库官方文档
'''
async def socket_server(websocket,port):
a = await websocket.recv()
print(f"{a}")
data = [['apple', 'egg', 'watermelon'],['red', 'yellow', 'green'],[30, 40, 50]]
data = json.dumps(data)
await websocket.send(data)
start_server = websockets.serve(socket_server,'localhost',8765)
'''
摘自 官方文档
loop.run_until_complete(future)
Run until the future (an instance of Future) has completed.
If the argument is a coroutine object it is implicitly scheduled to run as a asyncio.Task.
Return the Future’s result or raise its exception.
'''
asyncio.get_event_loop().run_until_complete(start_server)
'''
开始接受连接,直到取消协程。取消serve_forever任务会导致服务器关闭。
This method can be called if the server is already accepting connections.
Only one serve_forever task can exist per one Server object.
'''
asyncio.get_event_loop().run_forever()
js部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script type="text/javascript">
// https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket
// MDN websockt 文档
function sendInfo(){
console.log("start")
// 协议标识符是ws
var connection = new WebSocket("ws://localhost:8765/")
// 发送数据
connection.onopen = function (){
connection.send("i need dataframe!")
}
// 接收数据
connection.onmessage = function (evt){
let received_dataframe = evt.data
alert(received_dataframe)
connection.close()
}
console.log("end")
}
</script>
<body>
<button style="width: 300px;height: 300px" onclick="sendInfo()">发送数据</button>
</body>
</html>
|