python(server) javascript(client) 做websocket

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值