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()
    
  • 相关阅读:
    PAIRING WORKFLOW MANAGER 1.0 WITH SHAREPOINT 2013
    Education resources from Microsoft
    upgrade to sql server 2012
    ULSViewer sharepoint 2013 log viewer
    Top 10 Most Valuable Microsoft SharePoint 2010 Books
    讨论 Setsockopt选项
    使用 Alchemy 技术编译 C 语言程序为 Flex 可调用的 SWC
    Nagle's algorithm
    Nagle算法 TCP_NODELAY和TCP_CORK
    Design issues Sending small data segments over TCP with Winsock
  • 原文地址:https://www.cnblogs.com/GXLo/p/7405546.html
Copyright © 2011-2022 走看看