精华内容
下载资源
问答
  • 第一种, 使用create_connection链接,需要pip install websocket-client (此方法不建议使用,链接不稳定,容易断,并且连接很耗时) import time from websocket import create_connection url = 'wss://i.cg.net/...
  • ws = websocket.WebSocketApp(ws://echo.websocket.org/, on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever()  长连接,参数介绍: (1)url: ...
  • 主要介绍了Python Websocket服务端通信的使用示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • Python Websocket

    千次阅读 2018-07-27 11:52:59
    python django-admin.py startproject dj_websocket 2、进入项目 cd dj_websocket 3、创建APP(myapp) python manage.py startapp myapp 4、创建,static (静态文件夹),已经 templates(模板文件夹) mkdi...

    1 django dwebsocket 模块

    一、创建项目(dj_websocket):
    1、创建项目
    python django-admin.py startproject dj_websocket
    2、进入项目
    cd dj_websocket
    3、创建APP(myapp)
    python manage.py startapp myapp
    4、创建,static (静态文件夹),已经 templates(模板文件夹)
    mkdir static
    mkdir templates

    二、配置 settings.py

    1、在 INSTALLED_APPS 列表加上(myapp):
    INSTALLED_APPS = [
    	...,
        'myapp',
    ]
    
    2、在 TEMPLATES 列表的DIRS加上:
    TEMPLATES = [
        {
            ...,
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            ...,
        },
    ]
    
    3、在文件末尾加上:
    STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
    

    三、views.py 文件编写:

    import json
    import time
    import datetime
    from django.shortcuts import render
    from dwebsocket.decorators import accept_websocket,require_websocket
    
    # Create your views here.
    
    
    
    def index(request):
        return render(request, 'index.html',{'init':'init'})
    
    
    @accept_websocket
    def echo(request):
        if not request.is_websocket():#判断是不是websocket连接
        	#如果是普通的http方法
            try:
                message = request.GET['message']
                return HttpResponse(message)
            except:
                return render(request,'index.html')
        else:
        	# 如果是websocket请求
            for message in request.websocket:
                request.websocket.send(message)#发送消息到客户端
                #request.websocket.send(message)
                # 推送10次,当然你可以无限次的推送
                for i in range(10):
                    dt = str(datetime.datetime.now())
                    s={'test':f"你好 {i} {dt}"}
                    s=json.dumps(s).encode()
                    request.websocket.send(s)
                    time.sleep(0.1) # 间隔0.1秒
    
    

    四、urls.py 文件编写:

    from django.conf.urls import url
    from django.contrib import admin
    
    from myapp import views
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^index/', views.index),
        url(r'^echo$', views.echo),
    ]
    

    五、index.html 编写(templates文件夹)
    其中使用了 jquery-1.8.3.min.js ,需要下载到我们的 static 文件夹

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>django-websocket</title>
        {% load staticfiles %}
        <script src="{% static 'jquery-1.8.3.min.js' %}"></script>
        <script type="text/javascript">//<![CDATA[
        $(function () {
                /*创建socket连接
                var socket = new WebSocket("ws://" + window.location.host + "/echo");
                socket.onopen = function () {
                    console.log('WebSocket open');//成功连接上Websocket
                     socket.send($('#message').val());//通过websocket发送数据
                };
                socket.onmessage = function (e) {
                    console.log('message: ' + e.data);//打印出服务端返回过来的数据
                    $('#messagecontainer').prepend('<p>' + e.data + '</p>');
                };
                // Call onopen directly if socket is already open
                //if (socket.readyState == WebSocket.OPEN) socket.onopen();
                // 这些代码可以实现一进入页面就自动推送,不可停止
                */
    
            $('#connect_websocket').click(function () {
                if (window.s) {
                    window.s.close();
                }
                /*创建socket连接*/
                var socket = new WebSocket("ws://" + window.location.host + "/echo");
                socket.onopen = function () {
                    console.log('WebSocket open');//成功连接上Websocket
                };
                socket.onmessage = function (e) {
                    console.log('message: ' + e.data);//打印出服务端返回过来的数据
                    var d= $.parseJSON(e.data);
                    //alert(typeof(d));
                    $('#messagecontainer').prepend('<p>' + d.test + '</p>');
                };
                // Call onopen directly if socket is already open
                if (socket.readyState == WebSocket.OPEN) socket.onopen();
                window.s = socket;
            });
            $('#send_message').click(function () {
                //如果未连接到websocket
                if (!window.s) {
                    alert("websocket未连接.");
                } else {
                    window.s.send($('#message').val());//通过websocket发送数据
                }
            });
            $('#close_websocket').click(function () {
                if (window.s) {
                    window.s.close();//关闭websocket
                    console.log('websocket已关闭');
                }
            });
    
        });
        //]]></script>
    </head>
    <body>
    <br>
    <input type="text" id="message" value="开始..."/>
    <button type="button" id="connect_websocket">连接 websocket</button>
    <button type="button" id="send_message">发送 message</button>
    <button type="button" id="close_websocket">关闭 websocket</button>
    <h1>Received Messages</h1>
    <div id="messagecontainer">
    
    </div>
    {{init}}
    </body>
    </html>
    
    

    六、开始执行:
    这两句在这里不是必要的
    python manage.py makemigrations
    python manage.py migrate

    运行服务器
    python manage.py runserver

    七、访问:
    打开浏览器输入地址:http://localhost:8000/index/
    我们将看到页面:
    img1

    点击连接,再点击发送,开始推送:
    这里写图片描述

    2 websockets 模块

    **1 server.py **

    import websockets
    import asyncio
    import time
    import datetime
    import json
    
    async def hello(websocket,path):
      name = await websocket.recv()
      print(f'A new client: {name}')
      for i in range(10):
        dt = str(datetime.datetime.now())
        s = json.dumps({'test':f"{name} {i} {dt}"})
        await websocket.send(s)
        print(f'send {name} {i} {dt}')
        time.sleep(0.1)
    
    
    start_server = websockets.serve(hello,'localhost',8000)
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
    
    

    run server.py:
    python server.py

    **2 client.py **

    import websockets
    import asyncio
    
    
    async def hello():
      async with websockets.connect('ws://localhost:8000') as websocket:
        name = input("what's your name?")
        await websocket.send(name)
        print(f"send server:{name}")
        while 1:
          greeting = await websocket.recv()
          print(f'receive from server:{greeting}')
    
    asyncio.get_event_loop().run_until_complete(hello())
    
    

    run client.py
    python client.py
    input:hello
    output to server

    A new client: hello
    send hello 0 2018-07-28 20:24:11.410886
    send hello 1 2018-07-28 20:24:11.511604
    send hello 2 2018-07-28 20:24:11.612339
    send hello 3 2018-07-28 20:24:11.713062
    send hello 4 2018-07-28 20:24:11.813771
    send hello 5 2018-07-28 20:24:11.914492
    send hello 6 2018-07-28 20:24:12.015099
    send hello 7 2018-07-28 20:24:12.115936
    send hello 8 2018-07-28 20:24:12.216658
    send hello 9 2018-07-28 20:24:12.317399
    

    output to client.py

    what's your name?hello
    send server:hello
    receive from server:{"test": "hello 0 2018-07-28 20:24:11.410886"}
    receive from server:{"test": "hello 1 2018-07-28 20:24:11.511604"}
    receive from server:{"test": "hello 2 2018-07-28 20:24:11.612339"}
    receive from server:{"test": "hello 3 2018-07-28 20:24:11.713062"}
    receive from server:{"test": "hello 4 2018-07-28 20:24:11.813771"}
    receive from server:{"test": "hello 5 2018-07-28 20:24:11.914492"}
    receive from server:{"test": "hello 6 2018-07-28 20:24:12.015099"}
    receive from server:{"test": "hello 7 2018-07-28 20:24:12.115936"}
    receive from server:{"test": "hello 8 2018-07-28 20:24:12.216658"}
    receive from server:{"test": "hello 9 2018-07-28 20:24:12.317399"}
    
    

    3 client.html

    <html>
    <head>
        <meta charset="utf-8">
        <title>django-websocket</title>
        <script src="jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#connect_websocket').click(function () {
                if (window.s) {
                    window.s.close();
                }
                /*创建socket连接*/
                var socket = new WebSocket("ws://localhost:8000");
                socket.onopen = function () {
                    console.log('WebSocket open');//成功连接上Websocket
                };
                socket.onmessage = function (e) {
                    console.log('message: ' + e.data);//打印出服务端返回过来的数据
                    var d= $.parseJSON(e.data);
                    $('#messagecontainer').prepend('<p>' + d.test + '</p>');
                };
                if (socket.readyState == WebSocket.OPEN) socket.onopen();
                window.s = socket;
            });
            $('#send_message').click(function () {
                //如果未连接到websocket
                if (!window.s) {
                    alert("websocket未连接.");
                } else {
                    window.s.send($('#message').val());//通过websocket发送数据
                }
            });
            $('#close_websocket').click(function () {
                if (window.s) {
                    window.s.close();//关闭websocket
                    console.log('websocket已关闭');
                }
            });
    
        });
    </script>
    </head>
    <body>
    <br>
    <input type="text" id="message" value="开始..."/>
    <button type="button" id="connect_websocket">连接 websocket</button>
    <button type="button" id="send_message">发送 message</button>
    <button type="button" id="close_websocket">关闭 websocket</button>
    
    <div id="messagecontainer">
    
    </div>
    </body>
    </html>
    

    run client.html
    打开浏览器输入地址:file:///home/huang/Practise/demo1/client.html

    输入 :你好,点击连接,再点击发送,开始推送:
    output to server

    A new client: 你好
    send 你好 0 2018-07-28 20:38:34.384413
    send 你好 1 2018-07-28 20:38:34.485158
    send 你好 2 2018-07-28 20:38:34.585793
    send 你好 3 2018-07-28 20:38:34.686401
    send 你好 4 2018-07-28 20:38:34.787105
    send 你好 5 2018-07-28 20:38:34.887769
    send 你好 6 2018-07-28 20:38:34.988483
    send 你好 7 2018-07-28 20:38:35.089176
    send 你好 8 2018-07-28 20:38:35.189867
    send 你好 9 2018-07-28 20:38:35.290481
    
    

    output to client.html

    你好 9 2018-07-28 20:38:35.290481
    
    你好 8 2018-07-28 20:38:35.189867
    
    你好 7 2018-07-28 20:38:35.089176
    
    你好 6 2018-07-28 20:38:34.988483
    
    你好 5 2018-07-28 20:38:34.887769
    
    你好 4 2018-07-28 20:38:34.787105
    
    你好 3 2018-07-28 20:38:34.686401
    
    你好 2 2018-07-28 20:38:34.585793
    
    你好 1 2018-07-28 20:38:34.485158
    
    你好 0 2018-07-28 20:38:34.384413
    
    

    3 websockets 模块模拟动态推送K线图数据回测

    1、web_server.py

    import json
    import time
    import random
    import datetime
    import asyncio
    import websockets
    
    async def echo2(websocket, path):
        message = await websocket.recv()
        await websocket.send(message)
    
    @asyncio.coroutine
    def echo(websocket, path):
        message = yield from websocket.recv()
        print('recv', message)
        dt = datetime.datetime.now()
        cc = 1000
        for i in range(1000):
            dt2 = str(dt + datetime.timedelta(minutes=i))[11:19]
            y = [cc + random.randint(-80, 100) for i in range(4)]
            v = []
            mi = min(y)
            ma = max(y)
            y.remove(mi)
            y.remove(ma)
            y = [y[0], y[1], mi, ma]
            cc = y[2] if y[2] > 900 else 1000
            s = {'datetime': dt2, 'topic': 'bar','open':y[0],'close':y[1],'high':y[2],'low':y[3]}
            s = json.dumps(s)#.encode()
            #print(s)
            # request.websocket.send(s)
            yield from websocket.send(s)
    
            v = random.randint(0,5)
            if v in (3,4):
                v = 'SELL' if v==4 else 'BULL' # 卖出、买入
                s = {'topic':'trade','trading_dt':dt2,'price':y[1],'side':v}
                print(s)
            s = json.dumps(s)#.encode()
    
            # request.websocket.send(s)
            yield from websocket.send(s)
    
            time.sleep(0.5)  # 间隔0.5秒
    
    
    start_server = websockets.serve(echo, 'localhost', 8000)
    
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
    

    2 web_client.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>django-websocket</title>
        <script type="text/javascript" src="jquery-1.8.3.min.js"></script>
        <script type="text/javascript" src="echarts.min.js"></script>
    </head>
    <body>
    <br>
    <input type="text" id="message" value="200"/>
    <button type="button" id="connect_websocket">连接</button>
    <button type="button" id="send_message">开始画图</button>
    <button type="button" id="close_ht">暂停画图</button>
    <button type="button" id="close_websocket">关闭接收数据</button>
    <div id="messagecontainer">
    
    </div>
    <div id="main" style="width: auto;height: 800px;" align="center"></div>
        <script type="text/javascript">
    
    var myChart = echarts.init(document.getElementById('main'));
    var bs = new Array();
    var xzs = new Array();
    
    option = {
        title : {
            text: '回测',
            subtext: 'K线'
        },
        tooltip : {
            trigger: 'axis'
        },
        legend: {
            data:['回测','卖出','买入']
        },
        toolbox: {
            show : true,
            feature : {
                mark : {show: true},
                dataView : {show: true, readOnly: false},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        dataZoom : {
            show : true,
            realtime: true,
            start : 50,
            end : 100
        },
        xAxis : [
            {
                type : 'category',
                boundaryGap : true,
                data : [
    
                ]
            }
        ],
        yAxis : [
            {
                type : 'value',
                scale:true,
                splitNumber: 5,
                boundaryGap: [0.05, 0.05]
            }
        ],
        series : [
            {
                name:'回测',
                type:'k',
                data:[ // 开盘,收盘,最低,最高
                ]
            },{
                name:'卖出',
                type:'scatter',
                symbol: 'arrow',//'star3',
                symbolSize: 12,
                smooth:true,
                symbolRotate:180,
    
                itemStyle:{
                    //symbolRotate:-90,
                    normal: { color:function(p){
                        return bs[p.name];
                     }
                    }
                },
                
                data: []
            },{
                name:'买入',
                type:'scatter',
                symbol: 'arrow',//'star3',
                symbolSize: 12,
                smooth:true,
                symbolRotate:0,
    
                itemStyle:{
                    //symbolRotate:-90,
                    normal: { color:function(p){
                        return bs[p.name];
                     }
                    }
                },
                
                data: []
            }
        ]
    };
    
    stringToDate = function(dateStr,separator){
         if(!separator){
                separator="-";
         }
         var dateArr = dateStr.split(separator);
         var year = parseInt(dateArr[0]);
         var month;
         //处理月份为04这样的情况
         if(dateArr[1].indexOf("0") == 0){
             month = parseInt(dateArr[1].substring(1));
         }else{
              month = parseInt(dateArr[1]);
         }
         var day = parseInt(dateArr[2]);
         var date = new Date(year,month -1,day);
         return date;
     }
    
    var k_x = new Array();
    var k_y = new Array();
    var y_x = new Array();
    var y_y = new Array();
    var y_y2 = new Array();
    var is_huatu = true;
    var size = $('#message').val()-0;
    
    //myChart.setOption(option);
    
    function timeTicket(x,y,type,side){
        // 动态数据接口 addData
        // lastIndex += 1;
        // var len2 = option.series[0].data.length;
        // var d = option.xAxis[0].data[len2-1];
        // d = stringToDate(d,'/');
        // d.setDate(d.getDate()+1);
        // d = d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate();
    
        if(type=='k'){
            var ind = k_x.indexOf(x);
            if(ind<0){
                    k_x.push(x);
                    k_y.push(y);
                    y_y.push('');
                    y_y2.push('');
                }else{
                    k_y[ind] = y;
                }
                
                if(is_huatu){
                    option.xAxis[0].data=k_x.slice(-size);
                    option.series[0].data=k_y.slice(-size);
                    option.series[1].data=y_y.slice(-size);
                    option.series[2].data=y_y2.slice(-size);
                    //option.series[1].symbolRotate=y_y.slice(-size);
                    myChart.setOption(option);
                }
        }else if(type=='y'){
                var ind = k_x.indexOf(x);
                
                if(ind<0){
                    k_x.push(x);
                    k_y.push(k_y[k_y.length-1]);
                    if(side=='SELL'){
                        y_y.push(y);
                        y_y2.push('')
                    }else{
                        y_y.push('');
                        y_y2.push(y)
                    }
                }else{
                    //y_y[ind] = y;
                    if(side=='SELL'){
                        y_y[ind] = y;
                    }else{
                       y_y2[ind] = y;
                    }
                }
                if(is_huatu){
                    option.xAxis[0].data=k_x.slice(-size);
                    option.series[0].data=k_y.slice(-size);
                    option.series[1].data=y_y.slice(-size);
                    option.series[2].data=y_y2.slice(-size);
                   myChart.setOption(option);
                }
        }else{
            option.xAxis[0].data=k_x.slice(-size);
            option.series[0].data=k_y.slice(-size);
            option.series[1].data=y_y.slice(-size);
            option.series[2].data=y_y2.slice(-size);
            myChart.setOption(option);
        }
            /*myChart.addData([
                [
                    0,        // 系列索引
                    option.series[0].data[lastIndex%len], // 新增数据
                    false,     // 新增数据是否从队列头部插入
                    false,     // 是否增加队列长度,false则自定删除原有数据,队头插入删队尾,队尾插入删队头
                    d //option.xAxis[0].data[lastIndex%len]
                ]
            ]);*/
    }
    
    $(function () {
            function manages(info){
                if (window.s) {
                    window.s.close();
                }
                /*创建socket连接*/
                var url = "ws://localhost:8000"; // 连接地址
                var socket = new WebSocket(url); //window.location.host
                socket.onopen = function () {
                    console.log('WebSocket open');//成功连接上Websocket
                    if(info) alert('WebSocket open');
                };
                var x=null,y=null;
                socket.onmessage = function (e) {
                    console.log('message: ' + e.data);//打印出服务端返回过来的数据
                    var d= $.parseJSON(e.data);
                    if(d.topic=='bar'){
                        x = d.datetime;
                        y=[d.open,d.close,d.high,d.low]
                        timeTicket(x,y,'k','');
                    }else if(d.topic=='trade'){
                        x = d.trading_dt;
                        y = d.price;
                        //bs = d.bs;
                        if(d.side=='SELL'){
                            bs[x]='green';
                        }else{
                            bs[x]='red';
                        }
                        timeTicket(x,y,'y',d.side);
                    }
                };
                // Call onopen directly if socket is already open
                if (socket.readyState == WebSocket.OPEN) socket.onopen();
                window.s = socket;
            }
            manages(false);
            $('#connect_websocket').click(function () {
                manages(true);
            });
            $('#send_message').click(function () {
                //如果未连接到websocket
                is_huatu = true;
                if (!window.s) {
                    alert("websocket未连接.");
                } else {
                    window.s.send($('#message').val());//通过websocket发送数据
                }
            });
            $('#close_websocket').click(function () {
                if (window.s) {
                    window.s.close();//关闭websocket
                    console.log('websocket已关闭');
                }
            });
            $('#close_ht').click(function () {
                is_huatu = false;
                size = $('#message').val()-0;
                timeTicket('','','','');
            });
        });
    
    
    //var t=setInterval("timeTicket()",100);
    </script>
    </body>
    </html>
    

    3 执行
    1、python web_server.py
    2、浏览器打开:web_client.html,点击开始画图

    服务端输出结果:

    D:\tools>python server_web.py
    recv 200
    {'topic': 'trade', 'trading_dt': '18:58:22', 'price': 882, 'side': 'BULL'}
    {'topic': 'trade', 'trading_dt': '18:59:22', 'price': 1032, 'side': 'BULL'}
    {'topic': 'trade', 'trading_dt': '19:01:22', 'price': 856, 'side': 'BULL'}
    。。。。。。
    

    浏览器输出结果:
    这里写图片描述
    注:此代码只是个人根据当时的环境满足了当时的需求,记录下来用做后续参考!如有问题,请检查软硬件环境是否一致,由于时间精力有限,大部分未做详细环境描述。

    展开全文
  • 本次,我将从主流的三方框架使用出发,带大家熟悉和使用 Python 中常见的 websocket 库。 一、websocket-client 库 websocket-client 库是一个简单好用的同步的 websocket 的客户端的库,基于回调的方式使用。 pypi...

    ____tz_zs
    本次,我将从主流的三方框架使用出发,带大家熟悉和使用 Python 中常见的 websocket 库。

    一、websocket-client 库

    websocket-client 库是一个简单好用的同步的 websocket 的客户端的库,基于回调的方式使用。

    pypi地址: https://pypi.org/project/websocket-client/
    GitHub地址: https://github.com/websocket-client/websocket-client
    文档地址: https://websocket-client.readthedocs.io/en/latest/

    websocket-client 库也是我们诸多项目中正在使用的 websocket 库,这个库开箱即用,非常的方便,其 WebSocketApp 适合于建立长期连接。

    我们使用对象的函数作为 WebSocketApp 的回调函数,可以在全局变量中缓存和共享数据,持有 websocket 引用以便使用和关闭,维护长链接和心跳等,这种方式在构建应用程序时具有更大的灵活性。

    下方为 WebSocketApp 的一个使用例子,创建 WebSocketApp 对象,传入 url 地址,指定 on_open 等回调函数,调用 run_forever 运行。

    tips:
    1、 websocket.enableTrace(True) 可以开启运行状态追踪。debug 的时候最好打开他,便于追踪定位问题。
    2、也可以先创建对象,之后再使用如 self.ws.on_open = self.on_open 来指定回调函数。只需在 run_forever() 之前指定回调函数即可。
    3、控制台输出的 send: b'\x8a\x80\xf4-\xd9\x8b' 等形式的信息,是框架的开启运行状态追踪的输出信息(框架的输出log)

    (一)简单的使用demo

    # -*- coding:utf-8 -*-
    
    """
    @author:    tz_zs
    """
    
    import websocket
    from websocket import WebSocketApp
    
    try:
        import thread
    except ImportError:
        import _thread as thread
    import time
    
    
    class Test(object):
        def __init__(self):
            super(Test, self).__init__()
            self.url = "ws://echo.websocket.org/"
            self.ws = None
    
        def on_message(self, message):
            print("####### on_message #######")
            print("message:%s" % message)
    
        def on_error(self, error):
            print("####### on_error #######")
            print("error:%s" % error)
    
        def on_close(self):
            print("####### on_close #######")
    
        def on_ping(self, message):
            print("####### on_ping #######")
            print("ping message:%s" % message)
    
        def on_pong(self, message):
            print("####### on_pong #######")
            print("pong message:%s" % message)
    
        def on_open(self):
            print("####### on_open #######")
    
            thread.start_new_thread(self.run, ())
    
        def run(self, *args):
            while True:
                time.sleep(1)
                input_msg = input("输入要发送的消息(ps:输入关键词 close 结束程序):\n")
                if input_msg == "close":
                    self.ws.close()  # 关闭
                    print("thread terminating...")
                    break
                else:
                    self.ws.send(input_msg)
    
        def start(self):
            websocket.enableTrace(True)  # 开启运行状态追踪。debug 的时候最好打开他,便于追踪定位问题。
    
            self.ws = WebSocketApp(self.url,
                                   on_open=self.on_open,
                                   on_message=self.on_message,
                                   on_error=self.on_error,
                                   on_close=self.on_close)
            # self.ws.on_open = self.on_open  # 也可以先创建对象再这样指定回调函数。run_forever 之前指定回调函数即可。
    
            self.ws.run_forever()
    
    
    if __name__ == '__main__':
        Test().start()
    
    """
    --- request header ---
    GET / HTTP/1.1
    Upgrade: websocket
    Host: echo.websocket.org
    Origin: http://echo.websocket.org
    Sec-WebSocket-Key: AXR9yvs3Ucn9LE35KkhXfw==
    Sec-WebSocket-Version: 13
    Connection: upgrade
    
    
    -----------------------
    --- response header ---
    HTTP/1.1 101 Web Socket Protocol Handshake
    Connection: Upgrade
    Date: Wed, 04 Aug 2021 06:29:05 GMT
    Sec-WebSocket-Accept: WoOPLeAQpWaV2Bqd4sDOFkSpUuw=
    Server: Kaazing Gateway
    Upgrade: websocket
    -----------------------
    ####### on_open #######
    输入要发送的消息(ps:输入关键词 close 结束程序):
    aaadbbbbb
    send: b'\x81\x89\x82-\xdfj\xe3L\xbe\x0e\xe0O\xbd\x08\xe0'
    ####### on_message #######
    message:aaadbbbbb
    输入要发送的消息(ps:输入关键词 close 结束程序):
    sakdnakjf
    send: b'\x81\x89\xa8\xe0g\x8b\xdb\x81\x0c\xef\xc6\x81\x0c\xe1\xce'
    ####### on_message #######
    message:sakdnakjf
    输入要发送的消息(ps:输入关键词 close 结束程序):
    123456
    send: b'\x81\x86(\x84>\xb7\x19\xb6\r\x83\x1d\xb2'
    ####### on_message #######
    message:123456
    输入要发送的消息(ps:输入关键词 close 结束程序):
    send: b'\x8a\x80.\xf3`+'
    send: b'\x8a\x80P\x0c\xc6W'
    send: b'\x8a\x807j\x03l'
    send: b'\x8a\x80\xd0\xac%v'
    send: b'\x8a\x80\xb9\x9do\x08'
    send: b'\x8a\x80s\xbb\xad\x8f'
    send: b'\x8a\x80\xf4-\xd9\x8b'
    close
    send: b'\x88\x82\xf5L>\xc4\xf6\xa4'
    ####### on_close #######
    
    Process finished with exit code 0
    
    """
    

    (二)通过 HTTP 或 SOCKS 代理进行连接

    很多时候,特别是在线下测试环境中时,我们常常需要代理去访问某些服务器。如下 demo 中分别使用 http 和 socks5。
    http_proxy_host 参数传入代理的 host 地址。
    http_proxy_port 参数传入代理的端口号。
    proxy_type 参数如果不填,默认为 "http",可选参数值有 'http', 'socks4', 'socks5', 'socks5h'

    使用 socks5 可能会少包 PySocks module not found,注意不要下错包了 pip install PySocksNo module named ‘socks’

    # -*- coding:utf-8 -*-
    
    """
    @author:    tz_zs
    """
    
    import websocket
    from websocket import WebSocketApp
    
    try:
        import thread
    except ImportError:
        import _thread as thread
    import time
    
    
    class Test(object):
        def __init__(self):
            super(Test, self).__init__()
            self.url = "ws://echo.websocket.org/"
            self.ws = None
    
        def on_message(self, message):
            print("####### on_message #######")
            print("message:%s" % message)
    
        def on_error(self, error):
            print("####### on_error #######")
            print("error:%s" % error)
    
        def on_close(self):
            print("####### on_close #######")
    
        def on_ping(self, message):
            print("####### on_ping #######")
            print("ping message:%s" % message)
    
        def on_pong(self, message):
            print("####### on_pong #######")
            print("pong message:%s" % message)
    
        def on_open(self):
            print("####### on_open #######")
    
            thread.start_new_thread(self.run, ())
    
        def run(self, *args):
            # for i in range(3):
            #     time.sleep(1)
            #     self.ws.send("Hello %d" % i)
    
            while True:
                time.sleep(1)
                input_msg = input("输入要发送的消息(ps:输入关键词 close 结束程序):\n")
                if input_msg == "close":
                    self.ws.close()  # 关闭
                    print("thread terminating...")
                    break
                else:
                    self.ws.send(input_msg)
    
        def start(self):
            websocket.enableTrace(True)  # 开启运行状态追踪。debug 的时候最好打开他,便于追踪定位问题。
    
            self.ws = WebSocketApp(self.url,
                                   on_open=self.on_open,
                                   on_message=self.on_message,
                                   on_error=self.on_error,
                                   on_close=self.on_close)
            # self.ws.on_open = self.on_open  # 也可以先创建对象再这样指定回调函数。run_forever 之前指定回调函数即可。
    
            self.ws.run_forever(http_proxy_host="192.168.1.110", http_proxy_port=8123, proxy_type='http')
            # self.ws.run_forever(http_proxy_host="192.168.1.110", http_proxy_port=1080, proxy_type='socks5')
    
    if __name__ == '__main__':
        Test().start()
    
    """
    Connecting proxy...
    --- request header ---
    CONNECT echo.websocket.org:80 HTTP/1.0
    
    
    -----------------------
    --- response header ---
    HTTP/1.1 200 Connection established
    -----------------------
    --- request header ---
    GET / HTTP/1.1
    Upgrade: websocket
    Host: echo.websocket.org
    Origin: http://echo.websocket.org
    Sec-WebSocket-Key: JvORoQC9F6tb639eFo5s+Q==
    Sec-WebSocket-Version: 13
    Connection: upgrade
    
    
    -----------------------
    --- response header ---
    HTTP/1.1 101 Web Socket Protocol Handshake
    Connection: Upgrade
    Date: Wed, 04 Aug 2021 07:23:32 GMT
    Sec-WebSocket-Accept: LyeriRX6MoTWDOUIwu3T1AhurSQ=
    Server: Kaazing Gateway
    Upgrade: websocket
    -----------------------
    ####### on_open #######
    输入要发送的消息(ps:输入关键词 close 结束程序):
    124
    send: b'\x81\x83b\x83c\xd5S\xb1W'
    ####### on_message #######
    message:124
    输入要发送的消息(ps:输入关键词 close 结束程序):
    743
    send: b'\x81\x83*\\\xe8d\x1dh\xdb'
    ####### on_message #######
    message:743
    输入要发送的消息(ps:输入关键词 close 结束程序):
    close
    send: b'\x88\x82\xaeS\xd6\x94\xad\xbb'
    ####### on_close #######thread terminating...
    
    
    Process finished with exit code 0
    """
    

    源码 site-packages/websocket/_http.py

    class proxy_info(object):
    
        def __init__(self, **options):
            self.type = options.get("proxy_type") or "http"
            if not(self.type in ['http', 'socks4', 'socks5', 'socks5h']):
                raise ValueError("proxy_type must be 'http', 'socks4', 'socks5' or 'socks5h'")
            self.host = options.get("http_proxy_host", None)
            if self.host:
                self.port = options.get("http_proxy_port", 0)
                self.auth = options.get("http_proxy_auth", None)
                self.no_proxy = options.get("http_no_proxy", None)
            else:
                self.port = 0
                self.auth = None
                self.no_proxy = None
    

    (三)ping 和 pong

    WebSocket 规范将 ping 和 pong 消息操作码定义为协议的一部分。使即使服务器和客户端之间没有传输数据,也可以保持长期连接处于活动状态。

    1、自动响应

    框架接收到服务器发来的 ping 帧时,会立刻自动调用下方的函数,将数据使用 pong 帧原样发送给服务器,然后才回调 on_ping 将数据给使用者。所以,服务器发送到 ping 帧,我们一般不需要处理,框架自动回应了。

    源码 site-packages/websocket/_core.py 297行

    def pong(self, payload):
        """
        send pong data.
    
        payload: data payload to send server.
        """
        if isinstance(payload, six.text_type):
            payload = payload.encode("utf-8")
        self.send(payload, ABNF.OPCODE_PONG)
    

    2、ping_interval

    设置参数 ping_interval 框架将每间隔时间后自动发送空内容的 ping 帧。如果不设置参数(默认参数为 0),则不自动发送。

    源码 site-packages/websocket/_core.py 287行

    def ping(self,payload=""):
        """
        send ping data.
    
        payload: data payload to send server.
        """
        if isinstance(payload, six.text_type):
            payload = payload.encode("utf-8")
        self.send(payload, ABNF.OPCODE_PING)
    

    3、ping_timeout

    但是,因为框架不是异步的,如果发生阻塞事件,ping/pong 可能会出现一些问题。所以一般需要设置 ping_timeout 超时时间。
    注意,当 ping_interval 和 ping_timeout 参数都设置了的时候,框架要求参数 ping_interval 的值需大于参数 ping_timeout。

    if ping_timeout and ping_interval and ping_interval <= ping_timeout:
        raise WebSocketException("Ensure ping_interval > ping_timeout")
    

    源码中发送空 ping 帧时,会保存发送时间 self.last_ping_tm ,接收到服务器返回的 pong 帧时,会保存接收时间 self.last_pong_tm,如果同时满足(1)当前的时间距离上次发送 ping 的时间间隔大于参数 ping_timeout,(2)上次发送 ping 之后没有收到 pong,或接收到 pong 的时间距离上次发送 ping 的时间间隔大于参数 ping_timeout。

    源码 site-packages/websocket/_app.py 294行

    def check():
        if (ping_timeout):
            has_timeout_expired = time.time() - self.last_ping_tm > ping_timeout
            has_pong_not_arrived_after_last_ping = self.last_pong_tm - self.last_ping_tm < 0
            has_pong_arrived_too_late = self.last_pong_tm - self.last_ping_tm > ping_timeout
    
            if (self.last_ping_tm
                    and has_timeout_expired
                    and (has_pong_not_arrived_after_last_ping or has_pong_arrived_too_late)):
                raise WebSocketTimeoutException("ping/pong timed out")
        return True
    

    4、例子

    如下 demo 中,设置 ping_interval 为 20, ping_timeout 为 10。

    # -*- coding:utf-8 -*-
    
    """
    @author:    tz_zs
    """
    
    import websocket
    from websocket import WebSocketApp, ABNF
    
    try:
        import thread
    except ImportError:
        import _thread as thread
    import time
    
    
    class Test(object):
        def __init__(self):
            super(Test, self).__init__()
            self.url = "ws://echo.websocket.org/"
            self.ws = None
    
        def on_message(self, message):
            print("####### on_message #######")
            print("message:%s" % message)
    
        def on_error(self, error):
            print("####### on_error #######")
            print("error:%s" % error)
    
        def on_close(self):
            print("####### on_close #######")
    
        def on_ping(self, message):
            print("####### on_ping #######")
            print("ping time:%s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            print("ping message:%s" % message)
    
        def on_pong(self, message):
            print("####### on_pong #######")
            print("pong time:%s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            print("pong message:%s" % message)
    
        def on_open(self):
            print("####### on_open #######")
    
            thread.start_new_thread(self.run, ())
    
        def run(self, *args):
            # for i in range(3):
            #     time.sleep(1)
            #     self.ws.send("Hello %d" % i)
    
            while True:
                time.sleep(1)
                input_msg = input("输入要发送的ping消息(ps:输入关键词 close 结束程序):\n")
                if input_msg == "close":
                    self.ws.close()  # 关闭
                    print("thread terminating...")
                    break
                else:
                    self.ws.send(input_msg, ABNF.OPCODE_PING)
                    # self.ws.send(input_msg)
    
        def start(self):
            websocket.enableTrace(True)  # 开启运行状态追踪。debug 的时候最好打开他,便于追踪定位问题。
    
            self.ws = WebSocketApp(self.url,
                                   on_open=self.on_open,
                                   on_message=self.on_message,
                                   on_error=self.on_error,
                                   on_close=self.on_close,
                                   on_ping=self.on_ping,
                                   on_pong=self.on_pong)
    
            self.ws.run_forever(ping_interval=20, ping_timeout=10)
    
    
    if __name__ == '__main__':
        Test().start()
    
    

    框架每 20 秒发送空内容的 ping,控制台输出如下:

    """
    --- request header ---
    GET / HTTP/1.1
    Upgrade: websocket
    Host: echo.websocket.org
    Origin: http://echo.websocket.org
    Sec-WebSocket-Key: MDsoARDQEI8/4YILiLGwHw==
    Sec-WebSocket-Version: 13
    Connection: upgrade
    
    
    -----------------------
    --- response header ---
    HTTP/1.1 101 Web Socket Protocol Handshake
    Connection: Upgrade
    Date: Wed, 04 Aug 2021 08:20:42 GMT
    Sec-WebSocket-Accept: QiNgZdxqfcpJIeKlV6Byezls2Gw=
    Server: Kaazing Gateway
    Upgrade: websocket
    -----------------------
    ####### on_open #######
    输入要发送的ping消息(ps:输入关键词 close 结束程序):
    send: b'\x89\x80J\x1cn\x8c'
    ####### on_pong #######
    pong time:2021-08-04 16:21:12
    pong message:b''
    send: b'\x89\x80_\xad\xa1\xd9'
    ####### on_pong #######
    pong time:2021-08-04 16:21:32
    pong message:b''
    send: b'\x89\x80\xb6$\xc9\x9d'
    ####### on_pong #######
    pong time:2021-08-04 16:21:52
    pong message:b''
    send: b'\x89\x80)\xc3\x1f\xdc'
    ####### on_pong #######
    pong time:2021-08-04 16:22:12
    pong message:b''
    send: b'\x89\x80\xcf|\xfa&'
    ####### on_pong #######
    pong time:2021-08-04 16:22:32
    pong message:b''
    send: b'\x89\x80\xe5\x19/\xf9'
    ####### on_pong #######
    pong time:2021-08-04 16:22:52
    pong message:b''
    send: b'\x89\x80\xfb\x9bA8'
    ####### on_pong #######
    pong time:2021-08-04 16:23:12
    pong message:b''
    send: b'\x89\x80\xfc\xaa\xa6}'
    ####### on_pong #######
    pong time:2021-08-04 16:23:32
    pong message:b''
    send: b'\x89\x80O\xa0\x0e\xb6'
    ####### on_pong #######
    pong time:2021-08-04 16:23:52
    pong message:b''
    
    """
    

    手动发送有内容的 ping,控制台输出如下:

    """
    --- request header ---
    GET / HTTP/1.1
    Upgrade: websocket
    Host: echo.websocket.org
    Origin: http://echo.websocket.org
    Sec-WebSocket-Key: Ovizd9gdVze4BCLhymQ92Q==
    Sec-WebSocket-Version: 13
    Connection: upgrade
    
    
    -----------------------
    --- response header ---
    ####### on_open #######
    HTTP/1.1 101 Web Socket Protocol Handshake
    Connection: Upgrade
    Date: Wed, 04 Aug 2021 08:26:07 GMT
    Sec-WebSocket-Accept: vTtPyDWKViUA88UgBaLep+qi+CI=
    Server: Kaazing Gateway
    Upgrade: websocket
    -----------------------
    输入要发送的ping消息(ps:输入关键词 close 结束程序):
    ping_test
    send: b'\x89\x89+\x81\x19$[\xe8wCt\xf5|W_'
    ####### on_pong #######
    pong time:2021-08-04 16:26:24
    pong message:b'ping_test'
    输入要发送的ping消息(ps:输入关键词 close 结束程序):
    ping1111111111
    send: b'\x89\x8e\xe3\x05\xbck\x93l\xd2\x0c\xd24\x8dZ\xd24\x8dZ\xd24'
    ####### on_pong #######
    pong time:2021-08-04 16:26:32
    pong message:b'ping1111111111'
    输入要发送的ping消息(ps:输入关键词 close 结束程序):
    send: b'\x89\x80#\x0e\xa8\xdd'
    ####### on_pong #######
    pong time:2021-08-04 16:26:37
    pong message:b''
    close
    send: b'\x88\x82-0\xd6\xbc.\xd8'
    ####### on_close #######
    
    Process finished with exit code 0
    
    """
    
    展开全文
  • 我们在做接口测试时,除了常见的http接口,还有一种比较多见,就是socket接口,今天讲解下怎么用Python进行websocket接口测试。 现在大多数用的都是websocket,那我们就先来安装一下websocket的安装包。 pip ...
  • if(mac not in clients): clients[mac] = websocket await websocket.send(message) async def sendmsg(mac,mssage): # if(websocket in clients): websocket = clients[mac] await websocket.send(mssage) async ...

    参考文章: https://blog.csdn.net/xietansheng/article/details/115558069

    服务器端

    import asyncio
    import websockets
    import asyncio
    import websockets
    from websockets.legacy.server import WebSocketServerProtocol
    import json
    import time
    import threading
    clients={}
    
    async def ws_handle(websocket: WebSocketServerProtocol, path: str):
        # if(websocket in clients):
    
        async for message in websocket:
            print(message)
            jsonmsg = json.loads(message)
           
            if("deviceMac" in jsonmsg):
                mac = jsonmsg["deviceMac"]
                if(mac not in clients):
                    clients[mac] = websocket
                
     
            await websocket.send(message)
    
    
    
    async def sendmsg(mac,mssage):
        # if(websocket in clients):
        websocket = clients[mac] 
        await websocket.send(mssage)
    
    
    
    async def main():
        async with websockets.serve(ws_handle, "127.0.0.1", 8080):
            await asyncio.Future()              # run forever
    
    
    def WebSocketServer():
        asyncio.run(main())
    
    thread = threading.Thread(target=WebSocketServer)
    thread.start()
     
    async def test():
        flag=0
        while(True):
            flag = flag + 1
            for client in clients: 
                await sendmsg(client, str(flag)+"haha") #依次给每个客户端都发一条信息 
            time.sleep(1)
    
    def asyntest():
        asyncio.run(test())
            
    thread2 = threading.Thread(target=asyntest)
    thread2.start()
     
    

    客户端

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://cdn.bootcss.com/jquery/3.2.0/jquery.js"></script>
    </head>
    <body>
        <div id="time" style="width: 300px;height: 50px;  text-align: center;line-height: 50px;margin-left: 40%;font-size: 20px"></div>
        <input type="button" onclick="sayhello()"  value="测试websocket"/>
    
        <script>
                window.ws = new WebSocket("ws://127.0.0.1:8080/");  //连接server
    
                window.ws.onmessage = function (event) {
                    content = document.createTextNode(event.data); // 接收数据
                    $("#time").html(content);
    
                };
     
                function  sayhello(params) { 
                    console.log('{"deviceMac":"testdev"}');
                    window.ws.send('{"deviceMac":"testdev"}');
                }
    
        </script>
        </body>
    </html>
    
    展开全文
  • Python WebSocket消息发送与接收

    千次阅读 2020-10-27 10:41:29
    "channel":"btc_usdt.deep"}' print(req) ws.send(req) if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("wss://axxxxxxx/websocketServer?module=chat&product=hs&roomid=...

    一、读取Excel

    import xlrd
    
    #读取excel文件
    def excel():
        wb = xlrd.open_workbook('C:\\Users\\Administrator\\PycharmProjects\\HB\\testFile\\case\\1024.xlsx')# 打开Excel文件
        sheet = wb.sheet_by_name('content')#通过excel表格名称(rank)获取工作表
        dat = []  #创建空list
        for a in range(sheet.nrows):  #循环读取表格内容(每次读取一行数据)
                    cells = sheet.row_values(a)  # 每行数据赋值给cells
                    data=str(cells[0])#因为表内可能存在多列数据,0代表第一列数据,1代表第二列,以此类推
                    dat.append(data) #把每次循环读取的数据插入到list
        return dat
    a = excel() #返回整个函数的值
    print(a)
    
    def test(a):   #a变量传入
        for b in a:  #循环读取a变量list
            print(b)
            return b
    test(a)
    

    二、requests请求循环发送消息

    import requests
    import json
    import time
    from readExcel2 import *
    
    
    url='https://xxxxxxxxxxxx/chat/user/speak'
    headers={"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyMzQ0MjYzMDAsImlzcyI6ImF1dGhfdG9rZW4iLCJkYXRhIjoie1widXNlcklkXCI6NzcwLFwibmlja25hbWVcIjpudWxsfSJ9.QGBQdPgBSjme5xSRNfuo0TluWtmRMrLCWrIzeKYx5rM","platform":'2','Content-Type': 'application/json;charset=UTF-8'}
    payload = {"version":"2.0.3","live_id":982744,"type":1,"platform":2,"content":"嘿嘿","channelid":"0","pkg":"ddd","event_id":260,"send_type":0}
    
    
    for i in excel():
    	# print(i)
    	payload["content"] = i
    	response = requests.post(headers=headers,url=url, data=json.dumps(payload))
    	time.sleep(1)
    # 休眠1秒
    	print(response.text)
    # 	print(json.dumps(response.text))
    	# s=json.dumps(response.text).encode("utf-8")
    	# f = open("text.txt",'wb')
    	# f.write(s+b"\r\n")
    	# f.close()
    

    三、Websocket拉取消息

    import websocket
    
    
    def on_message(ws, message):  # 服务器有数据更新时,主动推送过来的数据
        print(message)
    
    
    def on_error(ws, error):  # 程序报错时,就会触发on_error事件
        print(error)
    
    
    def on_close(ws):
        print("Connection closed")
    
    
    def on_open(ws):  # 连接到服务器之后就会触发on_open事件,这里用于send数据
        req = '{"event":"subscribe", "channel":"btc_usdt.deep"}'
        print(req)
        ws.send(req)
    
    
    if __name__ == "__main__":
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp("wss://axxxxxxx/websocketServer?module=chat&product=hs&roomid=982744&userid=820&accessToken=e76576a79e4d9155923ffa726e161ede",
                                    on_message=on_message,
                                    on_error=on_error,
                                    on_close=on_close)
        ws.on_open = on_open
        ws.run_forever(ping_timeout=30)
    
    
    展开全文
  • python websocket 参数

    2020-09-15 10:55:00
    websocket中就有建立连接connect、发送消息send等函数可供使用,但是websocket.WebSocketApp将这些都封装好了,只用在实例化的时候传入自定义函数即可,更方便。因此这里选择使用websocket.WebSocketApp来模拟客户...
  • 文章目录 需求: python制作的工具拿到语音识别结果,发送给koa后端,然后在vue前端显示出来,由于要实时显示,所以需要进行vue+koa+python websocket通信
  • websocket-client模块是PythonWebSocket客户端。 它提供对WebSockets的低级API的访问。 所有API均用于同步功能。 websocket-client仅支持 。 执照 BSD 文献资料 该项目的文档可在找到 贡献 请在查看贡献准则。 ...
  • python websocket通讯协议简单实现

    万次阅读 2020-05-02 23:51:04
    websocket 通常要实现C/S或者B/S架构的通讯时,会选择websocket通讯协议。websocket允许服务器主动给客户端发送消息,如果是在自动化控制做服务器的时候,可以考虑使用此协议。 服务端代码 首先得先安装 websocket-...
  • websocket-client 版本 0.57.0 (一)on_open 调用 run_forever 建立连接时,websocket 模块会先 源码 websocket/_app.py > 259 行 > self._callback(self.on_open) 函数 通知 on_open 回调函数,连接建立。 ...
  • python websocket 断线自动重连

    千次阅读 2020-04-18 21:23:56
    搜索了半天,网上都是什么心跳重连,人现在的包都装好了,不知道你们咋还那么多问题, 目前的问题是,客户端由于网络... websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://localhost:8000/ws", ...
  • Python websocket

    2021-09-01 17:11:54
    要克服http中无法点对点的客户端对客户之间的通信,就要使用websockets协议,而Python中早就有成熟的第三方库websocket,只需pip install websockets,而且官网文档写得非常好: ......
  • python实现websocket

    2019-03-07 10:11:36
    pythonwebsocket实现,供大家学习 websocket,实现tcp通信,替代轮询,commit等技术 良心推荐
  • 我用python搭建websocket client后控制端却没有回显,如图: ![图片说明](https://img-ask.csdn.net/upload/201804/08/1523190629_114523.png) 请问各位大牛,错误之处在哪,如何用python获取源源不断的json格式数据...
  • python websocket 发送字节集

    千次阅读 2019-05-16 20:38:14
    最近在研究一个直播的websocket协议,发送跟以往不一样, 它这个平台发送bytes ,会断开连接,之前都没遇到过,检查了几遍, 以为是组包出现了问题,后面将代码放到js测试了,组包是没问题的 然后就重新检查了一变,发送...
  • python websocket实时消息推送

    千次阅读 2019-03-13 15:00:00
    python websocket实时消息推送 十分想念顺店杂可。。。 本人写的渣,大神勿喷。 转载请附带本文链接,谢谢。 服务端代码 # -*- coding: utf-8 -*- # @Time : 2019/3/12 10:11 # @Author : 甄超锋 # @Email : ...
  • 我们使用python的channels库来使用Websocket HTTP接收数据: class MessageConsumer(generic_http.AsyncHttpConsumer): async def handle(self, message): # handle the message await channel_layer.group_...
  • python websocket 的异步实现:websockets

    千次阅读 2020-05-07 22:46:22
    官方文档: ...Getting started(Version: 8.1) 环境:python3.7及以上 安装 pip install websockets 测试 python -m websockets wss://echo.websocket.org/ 发送什么就返回什么 基本...
  • # -*- coding: utf-8 -*-import jsonimport websocketimport _thread as thread # try:# import thread# except ImportError:# import _thread as thread def on_message(self, message): # 第一个参数必须传递 ...
  • python websocket demo

    2020-09-28 17:20:18
    async def hello(websocket,path): print("") name = await websocket.recv() print(f"{name} is coming") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"{greeting}")
  • #pip3 install websocket-server from websocket_server import WebsocketServer # 当新的客户端连接时会提示 def new_client(client, server): print("当新的客户端连接时会提示:%s" % client['id']) server....
  • # pip install websocket-client from websocket import create_connection import time ws = create_connection("ws://localhost:5000/echo") ws.send("Hello, World") b = 20 while b > 0: time.sleep(1...
  • 一个最小的 Python Websocket 客户端。 目的是创建一个最小的、易于阅读、易于使用的基于 Pythonwebsocket 客户端。 基本上仍在进行中,但适用于大多数目的。 待办事项 目前仍在建设中。 主要的突出问题是: ...
  • Python WebSocket长连接心跳与短连接

    千次阅读 2018-08-16 15:51:00
    python websocket 安装 pip install websocket-client 先来看一下,长连接调用方式: ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_message = on_message, ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 19,180
精华内容 7,672
关键字:

pythonwebsocket

python 订阅