• python websocket服务


    WebSocket 是一个标准化协议,构建在 TCP 之上,能够在客户端和服务端之间建立一个全双工的通信渠道。这里的客户端和服务端通常是用户浏览器和 Web 服务器。在 WebSocket 诞生之前,如果我们想保持这样的一个长连接,就需要使用诸如长轮询、永久帧、Comet 等技术。而现今 WebSocket 已经得到了所有主流浏览器的支持,我们可以使用它开发出在线聊天室、游戏、实时仪表盘等软件。

    安装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客户端与服务端各自输出的日志。

  • 相关阅读:
    Flowplayer-一款免费的WEB视频播放器
    nginx windows 版 创建windows 服务
    Windows Service Wrapper
    angular模板加载 ----ng-template
    理解AngularJS的作用域Scope
    Jquery使用ajax以及angularjs 动态模板加载并进行渲染
    angular.element方法汇总以及AngularJS 动态添加元素和删除元素
    JavaScript文件中调用AngularJS内部方法或改变$scope变量
    The repository for high quality TypeScript type definitions
    jspm 是浏览器包管理工具
  • 原文地址:https://www.cnblogs.com/slqt/p/10860886.html
Copyright © 2020-2023  润新知