zoukankan      html  css  js  c++  java
  • Python连接webstocker获取消息

    简介(脚本都是根据网上资料改写)

    此脚本主要是客户觉得webstcket不稳定,所以编辑一个脚本,不停的请求web服务器,当发生错误时,脚本自动退出()。
    

    脚本内容

    脚本一

    # -*- coding:utf-8 -*-
    '''
    模块下载,帮助地址:https://github.com/liris/websocket-client#readme
    模块:websocket-client
    说明:websocket客户端
    弊端:不能接受websocket服务端返回的数据
    '''
    
    import websocket
    import thread
    import time
    
    
    #定义消息返回
    def on_message(ws, message):
        print message
    
    #定义错误返回
    def on_error(ws, error):
        print error
    
    #定义关闭返回
    def on_close(ws):
        print "### closed ###"
    
    def on_open(ws):
        #*args 默认没有k值
        def run(*args):
            time.sleep(2)
            #发送请求
            ws.send("请求参数")
            #延迟两秒,等待消息返回
            time.sleep(2)
            #关闭连接
            ws.close()
            print "thread terminating..."
        #开启一个线程,执行run函数
        thread.start_new_thread(run, ())
    
    i=0
    
    if __name__ == "__main__":
        while True:
            try:
                websocket.enableTrace(True)
                ws = websocket.WebSocketApp("wss://地址",
                                  on_message = on_message,
                                  on_error = on_error,
                                  on_close = on_close)
            #继续上面的on-open
                ws.on_open = on_open
            #执行上面的操作
                ws.run_forever()
                i = i + 1
                print "成功:%d" %i
            except Exception,e:
                print e
                exit(1)
    

    脚本2

    # -*- coding:utf-8 -*-
    
    '''
    模块下载,帮助地址:https://github.com/liris/websocket-client#readme
    模块:websocket-client
    说明:websocket客户端
    比较方便,可以根据自己的真实环境,进行改动
    '''
    
    from websocket import create_connection
    import requests
    import json
    
    #建立一个websocket连接
    ws = create_connection("ws://IP")
    #对websocket客户端发送一个请求
    ws.send("token")
    #使用一个变量,接受返回的数据
    result =  ws.recv()
    #打印返回的数据
    print result
    #关闭websocketqingq
    ws.close()
    
  • 相关阅读:
    4-MSP430定时器_定时器中断
    关于STM32的外部引脚中断的问题
    关于stm32的正交解码
    红外接收控制灯亮灭
    mack pro常用快捷键
    liunx操作系统安装<一>
    支付宝架构师:从工程师到架构师的成长之路
    maven之setting.xml的配置详解
    分布式之《保证分布式系统数据一致性的6种解决方案》
    Eclipse中jsp、js文件编辑时,卡死现象解决汇总
  • 原文地址:https://www.cnblogs.com/GXLo/p/7405546.html
Copyright © 2011-2022 走看看