我是靠谱客的博主 专一大门,这篇文章主要介绍python(server) javascript(client) 做websocket,现在分享给大家,希望可以做个参考。

python部分

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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部分

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!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)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部