概述
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>
最后
以上就是专一大门为你收集整理的python(server) javascript(client) 做websocket的全部内容,希望文章能够帮你解决python(server) javascript(client) 做websocket所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复