예제 #1
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        while True:
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'
                  .format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
예제 #2
0
async def startup(uri):
    while True:
        try:
            async with AioWebSocket(uri) as aws:
                converse = aws.manipulator
                msg = await converse.receive()
                x = msg.decode()
                userid = json.loads(x)["data"]["user"]["id"]

                # '{"cmd":7,"path":"/yuanda/node/books","user":{"id":"'+ f'{userid} }'}}'
                lc = LoginCommand(cmd=7, path='/yuanda/node/books', user=User(id=userid))
                lcp = lc.dumps()
                xx = LoginCommand.loads(lcp)
                print(xx.cmd)
                await converse.send(lcp)
                while True:
                    try:
                        mes = await converse.receive()
                        # await converse.receive()
                        print('{time}-Client receive: {rec}'
                              .format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes.decode()))
                        # await converse.writer.drain()
                    except (asyncio.IncompleteReadError, ConnectionError) as ex:
                        print(ex)
                        asyncio.sleep(5)
        except Exception as e:
            print(e)
            await asyncio.sleep(5)
예제 #3
0
async def startup(uri): # anync 异步语法
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # 客户端给服务端发送消息
        #await converse.send('{"action":"subscribe","args":["QuoteBin5m:14"]}') # await 也是异步语法
        await converse.send('{"event": "req", "params": {"channel": "review"}')
        #await converse.send('{"event":"sub","params":{"channel":"market_vdsusdt_ticker","cb_id":"vdsusdt"}}')
        await converse.send('{"event": "req", "params": {"channel": "market_btcusdt_trade_ticker", "cb_id": "btcusdt", "top": 100}}')
        await converse.send('{"event": "sub", "params": {"channel": "market_btcusdt_trade_ticker", "cb_id": "btcusdt", "top": 100}}')
        while True:
            mes = await converse.receive()
            mesUnPack = gzip.decompress(mes)
            mesJSON = json.loads(str(mesUnPack)[2:-1])
            #print(mesJSON)
            print('{time}-Client receive: {rec}'
             .format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mesUnPack))
            if('ping' in mesJSON):
                await converse.send('{"pong":'+str(mesJSON['ping'])+'}')
            else:
                if('tick' in mesJSON):
                    tickJSON = mesJSON['tick']
                    if(tickJSON is not None):
                        if('data' in tickJSON):
                            dataJSONArray = tickJSON['data']
                            for c in range(0, len(dataJSONArray)):
                                price = dataJSONArray[c]['price']
                                ds = dataJSONArray[c]['ds']
                                print("price:"+str(price)+";data:"+ds)
예제 #4
0
async def gate_spider():
    '''
    gate spider
    url: https://gateio.co/docs/futures/ws/index.html
    :return:
    '''
    print('gate_spider: start')
    uri = 'wss://fx-ws.gateio.ws/v4/ws'

    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator

        # 客户端给服务端发送消息
        # 行情
        # await converse.send('{"time" : 123456, "channel" : "futures.tickers", "event": "subscribe", "payload" : ["BTC_USD","EOS_USD"]}')
        # 实时交易
        # await converse.send('{"time" : 123456, "channel" : "futures.trades", "event": "subscribe", "payload" : ["BTC_USD","EOS_USD"]}')
        # 深度
        # await converse.send('{"time" : 123456, "channel" : "futures.order_book", "event": "subscribe", "payload" : ["BTC_USD", "20", "0"]}')
        # 蜡烛图/K线
        #await converse.send('{"time" : 123456, "channel" : "futures.candlesticks", "event": "subscribe", "payload" : ["10s", "BTC_USD"]}')
        await converse.send('{"time" : 123456, "channel" : "futures.candlesticks", "event": "subscribe", "payload" : ["15m", "BTC_USD"]}')
        await converse.send('{"time" : 123456, "channel" : "futures.candlesticks", "event": "subscribe", "payload" : ["1h", "BTC_USD"]}')
        await converse.send('{"time" : 123456, "channel" : "futures.candlesticks", "event": "subscribe", "payload" : ["4h", "BTC_USD"]}')
        await converse.send('{"time" : 123456, "channel" : "futures.candlesticks", "event": "subscribe", "payload" : ["1d", "BTC_USD"]}')

        while True:
            data = await converse.receive()
            if data:
                data = decode_ws_payload(data)
                await gate_parser(data)
            print('{time}-Client receive.'.format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
예제 #5
0
async def start_up(ws_url):
    async with AioWebSocket(ws_url) as ws:
        converse = ws.manipulator
        await converse.send('{"event": "ticker", "params": {"ids": [49653, 49654]}}')
        while True:
            recv = await converse.receive()
            print(recv)
예제 #6
0
async def startup(uri):
    async with AioWebSocket(remote) as aws:
        converse = aws.manipulator

        reqMsg = json.dumps({'sub': 'market.btcusdt.trade.detail', 'id': 1})
        await converse.send(reqMsg)
        while True:
            rec = await converse.receive()
            buff = BytesIO(rec)
            f = gzip.GzipFile(fileobj=buff)
            res = f.read().decode('utf-8')
            rj = json.loads(res)
            if 'ping' in rj:
                backmsg = json.dumps({'pong': rj['ping']})
                await converse.send(backmsg)
                print(res, backmsg)
            if 'tick' in rj:
                cursor = conn.cursor()
                for tick in rj['tick']['data']:
                    try:
                        cursor.execute(
                            'insert into tick (tradeId, price, amount, ts, direction) values (?,?,?,?,?)',
                            (tick['tradeId'], tick['price'], tick['amount'],
                             tick['ts'], tick['direction']))
                    except sqlite3.IntegrityError:
                        print(sqlite3.IntegrityError)
                cursor.close()
                conn.commit()
                print(rj['tick']['data'])
            else:
                print(rj)
예제 #7
0
async def startup(room_id: str):
    async with AioWebSocket(remote) as aws:
        converse = aws.manipulator
        await converse.send(get_data(roomid))
        tasks = asyncio.create_task(sendHeartBeat(converse, room_id))
        while True:
            recv_text = await converse.receive()
            printDM(recv_text)
예제 #8
0
 async def startup(self, url):
     data_raw = '000000{headerLen}0010000100000007000000017b22726f6f6d6964223a{roomid}7d'
     data_raw = data_raw.format(headerLen=hex(27 + len(self.roomID))[2:],
                                roomid=''.join(map(lambda x: hex(ord(x))[2:], list(self.roomID))))
     async with AioWebSocket(url) as aws:
         converse = aws.manipulator
         await converse.send(bytes.fromhex(data_raw))
         tasks = [self.receDM(converse), self.sendHeartBeat(converse)]
         await asyncio.wait(tasks)
예제 #9
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # 客户端给服务端发送消息
        await converse.send('{"action":"subscribe","args":["QuoteBin5m:14"]}')
        while True:
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
예제 #10
0
async def startup(uri):
	async with AioWebSocket(uri) as aws:
		converse = aws.manipulator
		message = 'print(123)'
		mes = await converse.receive()
		print('{time}-Client receive: {rec}'
			  .format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
		await converse.send(message)
		print('{time}-Client send: {message}'
			.format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), message=message))
예제 #11
0
파일: aiows.py 프로젝트: ynzheng/alphaquant
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # 客户端给服务端发送消息
        await converse.send(
            '{"method": "SUBSCRIBE","params":["btcusdt@aggTrade","btcusdt@depth"],"id": 1}'
        )
        while True:
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
예제 #12
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        # 初始化 aiowebsocket库的链接类
        converse = aws.manipulator
        # 设定需要传送的信息
        message = b'WTF'
        while True:
            # 不断地向服务器发送信息,并打印输出信息时间和信息内容
            await converse.send(message)
            mes = await converse.receive()
            print(mes)
예제 #13
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # 客户端给服务端发送消息
        await converse.send(data1)
        while True:
            mes = await converse.receive()
            try:
                print(str(mes, "utf-8"))
            except:
                print(mes)
예제 #14
0
 async def startup(self):
     url = r'wss://broadcastlv.chat.bilibili.com:2245/sub'
     data_raw = '000000{headerLen}0010000100000007000000017b22726f6f6d6964223a{roomid}7d'
     data_raw = data_raw.format(headerLen=hex(27 + len(self.roomID))[2:],
                                roomid=''.join(
                                    map(lambda x: hex(ord(x))[2:],
                                        list(self.roomID))))
     async with AioWebSocket(url) as aws:
         converse = aws.manipulator
         await converse.send(bytes.fromhex(data_raw))
         tasks = [self.recvDanmu(converse), self.sendHeartBeat(converse)]
         await asyncio.wait(tasks)
예제 #15
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        message = b'my test'
        while True:
            await converse.send(message)
            _time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print(f'{_time}-Client send: {message}')
            mes = await converse.receive()
            _time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            print(f'{_time}-Client receive: {mes}')
            time.sleep(1)
예제 #16
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator

        # 给服务端发送验证消息,观察网页接口数据动态获取
        message = '{"action":"subscribe","args":["QuoteBin5m:14"]}'
        await converse.send(message)

        while True:
            receive = await converse.receive()

            # 拿到的是byte类型数据,解码为字符串数据
            print(receive.decode())
예제 #17
0
async def startup(url):
    init_msg = '000000{len}0010000100000007000000017b22726f6f6d6964223a{room}7d'  # 初始化连接要求的信息
    room_id_hex = ''.join(map(lambda x: hex(ord(x))[2:],
                              list(room_id)))  # 直播间序号逐位转换到 ASCII 码的十六进制
    init_msg = init_msg.format(len=hex(27 + len(room_id))[2:],
                               room=room_id_hex)  # 填充包长和直播间序号字段

    async with AioWebSocket(url) as aws:  # 连接建立
        converse = aws.manipulator  # socket
        await converse.send(bytes.fromhex(init_msg))  # 发送初始化信息
        display('connection established')
        tasks = [heart_beat(converse), rcvmsg(converse)]  # 两个异步任务 - 发送心跳,接收信息
        await asyncio.wait(tasks)
예제 #18
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # 客户端给服务端发送消息

        await converse.send('{"H":"c2","M":"SubscribeToSummaryLiteDeltas","A":[],"I":0}')  # 监听所有市场
        await converse.send('{"H":"c2","M":"SubscribeToExchangeDeltas","A":["BTC-MANA"],"I":1}')  #
        await converse.send('{"H":"c2","M":"QueryExchangeState","A":["BTC-MANA"],"I":2}')


        while True:
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'
                  .format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
예제 #19
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator

        # 客户端给服务端发送消息
        await converse.send('{"id":956988,"method":"server.ping","params":[]}')
        #await converse.send('{"id":956988,"method":"depth.subscribe","params":["BTC_USDT",30,"0.01"]}')
        await converse.send('{"id":956988,"method":"trades.subscribe","params":["BTC_USDT"]}')
        #await converse.send('{"id":956988,"method":"price.subscribe","params":["BTC_USDT","BCH_USDT","ETH_USDT","ETC_USDT","QTUM_USDT","LTC_USDT","DASH_USDT","ZEC_USDT","BTM_USDT","EOS_USDT","REQ_USDT","SNT_USDT","OMG_USDT","PAY_USDT","CVC_USDT","ZRX_USDT","TNT_USDT","XMR_USDT","XRP_USDT","DOGE_USDT","BAT_USDT","PST_USDT","BTG_USDT","DPY_USDT","LRC_USDT","STORJ_USDT","RDN_USDT","STX_USDT","KNC_USDT","LINK_USDT","CDT_USDT","AE_USDT","RLC_USDT","RCN_USDT","TRX_USDT","KICK_USDT","VET_USDT","MCO_USDT","FUN_USDT","DATA_USDT","ZSC_USDT","MDA_USDT","XTZ_USDT","GNT_USDT","GEM_USDT","RFR_USDT","DADI_USDT","ABT_USDT","OST_USDT","XLM_USDT","MOBI_USDT","OCN_USDT","ZPT_USDT","COFI_USDT","JNT_USDT","BLZ_USDT","GXS_USDT","MTN_USDT","RUFF_USDT","TNC_USDT","ZIL_USDT","BTO_USDT","THETA_USDT","DDD_USDT","MKR_USDT","DAI_USDT","SMT_USDT","MDT_USDT","MANA_USDT","LUN_USDT","SALT_USDT","FUEL_USDT","ELF_USDT","DRGN_USDT","GTC_USDT","QLC_USDT","DBC_USDT","BNTY_USDT","LEND_USDT","ICX_USDT","BTF_USDT","ADA_USDT","LSK_USDT","WAVES_USDT","BIFI_USDT","MDS_USDT","DGD_USDT","QASH_USDT","POWR_USDT","FIL_USDT","BCD_USDT","SBTC_USDT","GOD_USDT","BCX_USDT","QSP_USDT","INK_USDT","MED_USDT","QBT_USDT","TSL_USDT","GNX_USDT","NEO_USDT","GAS_USDT","IOTA_USDT","NAS_USDT","OAX_USDT","BCDN_USDT","SNET_USDT","BTS_USDT","GT_USDT","ATOM_USDT","XEM_USDT","BU_USDT","BCHSV_USDT","DCR_USDT","BCN_USDT","XMC_USDT","PPS_USDT","ATP_USDT","NBOT_USDT","MEDX_USDT","GRIN_USDT","BEAM_USDT","BTT_USDT","TFUEL_USDT","CELR_USDT","CS_USDT","MAN_USDT","REM_USDT","LYM_USDT","ONG_USDT","ONT_USDT","BFT_USDT","IHT_USDT","SENC_USDT","TOMO_USDT","ELEC_USDT","HAV_USDT","SWTH_USDT","NKN_USDT","SOUL_USDT","LRN_USDT","EOSDAC_USDT","DOCK_USDT","GSE_USDT","RATING_USDT","HSC_USDT","HIT_USDT","DX_USDT","CNNS_USDT","DREP_USDT","MBL_USDT","GMAT_USDT","MIX_USDT","LAMB_USDT","LEO_USDT","WICC_USDT","SERO_USDT","VIDY_USDT","KGC_USDT","ARPA_USDT","ALGO_USDT","BKC_USDT","BXC_USDT","PAX_USDT","USDC_USDT","TUSD_USDT","HC_USDT","GARD_USDT","FTI_USDT","SOP_USDT","LEMO_USDT","QKC_USDT","IOTX_USDT","RED_USDT","LBA_USDT","OPEN_USDT","MITH_USDT","SKM_USDT","XVG_USDT","NANO_USDT","HT_USDT","BNB_USDT","MET_USDT","TCT_USDT","MXC_USDT"]}')
        #await converse.send('{"id":956988,"method":"kline.subscribe","params":["BTC_USDT",86400]}')

        while True:
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'
                  .format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
예제 #20
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # 客户端给服务端发送消息
        await converse.send(
            '{"action": "subscribe","args": ['
            '"Ticker:BTC/USDT", "Ticker:ETH/USDT", "Ticker:BCH/USDT", "Ticker:BSV/USDT", "Ticker:LTC/USDT",'
            '"Ticker:XRP/USDT", "Ticker:ETC/USDT", "Ticker:EOS/USDT", "Ticker:TRX/USDT", "Ticker:ADA/USDT",'
            '"Ticker:LINK/USDT", "Ticker:OKB/USDT", "Ticker:ALGO/USDT", "Ticker:ELF/USDT", "Ticker:AMBC/USDT",'
            '"Ticker:XDAG/USDT", "Ticker:DOGE/USDT", "Ticker:PRA/USDT", "Ticker:QSD/USDT" ]}'
        )
        while True:
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
예제 #21
0
async def huobi_spider():
    '''
    huobi spider
    url: https://huobiapi.github.io/docs/spot/v1/cn/
    :return:
    '''

    uri = 'wss://api.huobi.pro/ws'

    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator

        # 客户端给服务端发送消息
        # 行情
        # await converse.send('{ "sub": "market.btcusdt.detail", "id": "%s" }' % client_id)
        # 实时交易
        # await converse.send('{ "sub": "market.btcusdt.trade.detail", "id": "%s" }' % client_id)
        # 深度
        # await converse.send('{ "sub": "market.btcusdt.depth.step1", "id": "%s" }' % client_id)
        # 蜡烛图/K线
        await converse.send(
            '{ "sub": "market.btcusdt.kline.15min", "id": "%s" }' % client_id)
        await converse.send(
            '{ "sub": "market.btcusdt.kline.60min", "id": "%s" }' % client_id)
        await converse.send(
            '{ "sub": "market.btcusdt.kline.4hour", "id": "%s" }' % client_id)
        await converse.send(
            '{ "sub": "market.btcusdt.kline.1day", "id": "%s" }' % client_id)

        while True:
            data = await converse.receive()
            if data:
                try:
                    data = decode_ws_payload(data)
                    if 'ch' in data:
                        await huobi_parser(data)
                    elif 'ping' in data:
                        print('pong:', data['ping'])
                    else:
                        print("continue", data)
                        continue
                except Exception as e:
                    print(e, "decode failed.")
                except:
                    print("decode failed.")

            print('{time}-Client receive.'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
예제 #22
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        # 初始化 aiowebsocket 库的连接类
        converse = aws.manipulator
        # 设定需要向服务器发送的信息
        message = b'AioWebSocket - Async WebSocket Client'
        while True:
            # 不断的向服务器发送信息,并打印输出信息发送内容和时间
            await converse.send(message)
            print('{time}-Client send: {message}'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                message=message))
            # 不断的读取服务器推送给客户端的信息,并打印输出信息内容和时间
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
예제 #23
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # message = '{"sub":"market.btcusdt.trade.detail","symbol":"btcusdt"}'
        # message = '{"sub":"market.tickers","symbol":"htusdt"}'
        # 最近24小时成交量、成交额、开盘价、收盘价、最高价、最低价、成交笔数等
        message = '{"sub":"market.btcusdt.detail","symbol":"btcusdt"}'
        while True:
            await converse.send(message)
            # print('{time}-Client send: {message}'
            #       .format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), message=message))
            mes = await converse.receive()
            mes1 = gzip.decompress(mes).decode("utf-8")
            res = json.loads(mes1)
            print('{time}-Client receive: {rec}'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes1))
예제 #24
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # 向服务器发送消息
        await converse.send(
            '{"command":"RegisterInfo","action":"Web","ids":[],"UserInfo":{"Version":"['
            + str(int(time.time())) + '000' +
            ']{\\"chrome\\":true,\\"version\\":\\"86.0.4240.183\\",\\"webkit\\":true}","Url":"https://live.611.com/zq"}}'
        )
        await converse.send(
            '{"command":"JoinGroup","action":"SoccerLiveOdd","ids":[]}')
        await converse.send(
            '{"command":"JoinGroup","action":"SoccerLive","ids":[]}')
        while True:
            mes = await converse.receive()
            print(mes)
예제 #25
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        message = b'next'
        while True:
            await converse.send(message)
            print('{time}-Client send: {message}'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                message=message))
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'.format(
                time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
            imgData = base64.b64decode(mes)
            nparr = np.fromstring(imgData, np.uint8)
            img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            cv2.imshow('video', img_np)
            cv2.waitKey(delay=1)
예제 #26
0
async def startup(app, room_id: str):
    '''创建ws连接b站弹幕服务器'''
    async with AioWebSocket(remote) as aws:
        converse = aws.manipulator
        await converse.send(get_data(room_id))
        tasks = asyncio.create_task(sendHeartBeat(converse, room_id))
        t = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S,%f")
        t = t[:len(t) - 3] + ']'
        print('%s[NOTICE]: 开启对房间号%s的视奸' % (t, room_id))
        try:
            while True:
                recv_text = await converse.receive()
                await printDM(app, recv_text, room_id)
        except Exception as e:
            tasks.cancel()
            if str(e) == '断开连接':
                await asyncio.sleep(300)
            await asyncio.sleep(30)
예제 #27
0
async def startup(app, room_id: str):
    data = get_data(room_id)
    async with AioWebSocket(remote) as aws:
        converse = aws.manipulator
        await converse.send(data)

        data = await converse.receive()
        print(data)

        jd = json.loads(
            data[16:].decode('utf-8', errors='ignore'))
        if jd['code'] != 0:
            return
        t = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S,%f")
        t = t[:len(t) - 3] + ']'
        print('%s[NOTICE]: 开启对房间号%s的订阅' % (t, room_id))
        tasks = [receDM(app, converse, room_id), sendHeartBeat(converse,room_id)]
        await asyncio.wait(tasks)
예제 #28
0
async def get_effective_data(uri, message_type: str, log):
    connect_times = 0
    while True:
        connect_times += 1
        async with AioWebSocket(uri) as aws:
            converse = aws.manipulator
            await converse.send(message_type)
            mes = await converse.receive()
            mes1 = gzip.decompress(mes).decode("utf-8")
            res = json.loads(mes1)
            if "status" in res and res['status'].lower() == 'ok':
                return converse
            print(f'{uri} 链接失败,尝试第{str(connect_times)} 次链接', file=log)
            # await asyncio.sleep(random.randint(300, 900))
            await asyncio.sleep(random.randint(1, 10))
            if connect_times > 5:
                SendMessageTool.send_message_by_sms('')
                raise ('多次链接服务器错误, 请查看原因')
예제 #29
0
async def startup(uri, f):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        n = 0
        while True:
            mes = await converse.receive()
            mes = mes.decode()
            # print(mes)
            f.write(mes + '\n')
            mes_json = json.loads(mes)
            manage_danmu(mes_json)
            n += 1
            if n == 3:
                mid = mes_json['msgId']
                await converse.send(
                    '{"body":{"msgId":"%s"},"op":6,"sid":0,"seq":0} 	' % mid)
                n = 0
            else:
                await converse.send('{"body":"{}","op":2,"sid":0,"seq":0}	')
예제 #30
0
async def startup(uri):
    async with AioWebSocket(uri) as aws:
        converse = aws.manipulator
        # 客户端给服务端发送消息

        await converse.send('{"event":"pusher:subscribe","data":{"channel":"exchange_market"}}')  # 监听所有市场
        await converse.send('{"event":"pusher:subscribe","data":{"channel":"exchange_market_bid_ask"}}')  #

        # 监听btc_usdt webscoket
        # await converse.send('{"event":"pusher:subscribe","data":{"channel":"exchange_ticker"}}')
        # await converse.send('{"event":"pusher:subscribe","data":{"channel":"exchange_eth-usdt"}}')
        # await converse.send('{"event":"pusher:subscribe","data":{"channel":"exchange_bqqq-usdt"}}')
        # await converse.send('{"event":"pusher:subscribe","data":{"auth":"5174598ab656e4da66dc:1c303fad7f188e3a9f130235ecffc1a2052da5bd9645d572b8b6020f1d154032","channel":"private-exchange==abbd73ed-2cde-416f-8ce1-3217e0472205"}}')  # 监听所有市场

        while True:
            mes = await converse.receive()
            print('{time}-Client receive: {rec}'
                  .format(time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'), rec=mes))
            print(type(mes))