本文整理汇总了Python中websockets.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: monitor_pb
def monitor_pb(self):
first_run = True
obj = {}
ident = self.config['pb_key']
url = "wss://stream.pushbullet.com/websocket/%s" % ident
websocket = yield from websockets.connect(url)
irc.util.log("websocket %s connected" % websocket)
last = 0
while True:
obj = yield from websocket.recv()
if obj is None:
irc.util.log("websocket %s closed" % websocket)
irc.util.log("reconnecting")
websocket = yield from websockets.connect(url)
irc.util.log("websocket %s connected" % websocket)
obj = json.loads(obj)
if first_run or obj['type'] == 'tickle' and obj['subtype'] == 'push':
first_run = False
irc.util.log("event stream recieved %s" % obj)
pushes = yield from irc.aiopb.get_pushes(ident, last)
#pushes = irc.pb.get_pushes(ident, last)
irc.util.log("%s new pushes" % len(pushes))
if len(pushes) > 0 and 'modified' in pushes[0]:
last = pushes[0]['modified']
for push in pushes:
ret = yield from irc.aiopb.push_to_s(push)
self.privmsg(ret)
status = yield from irc.aiopb.dismiss_push(push, ident)
if status == 200:
irc.util.log("dismissed %s" % push['iden'])
else:
irc.util.log("error dismissing %s: %s" % (push['iden'], status))
示例2: hello
def hello():
websocket = yield from websockets.connect('ws://192.168.1.106:81/')
ws = yield from websockets.connect('ws://192.168.1.107:81/')
while True:
try:
option = input("What Do you want to do? ")
if option == "Led on":
yield from websocket.send(option)
print("> {}".format(option))
greeting = yield from websocket.recv()
print("< {}".format(greeting))
elif option == "Led off":
yield from websocket.send(option)
print("> {}".format(option))
greeting = yield from websocket.recv()
print("< {}".format(greeting))
elif option == "Lamp on":
yield from websocket.send(option)
print("> {}".format(option))
greeting = yield from websocket.recv()
print("< {}".format(greeting))
elif option == "Lamp off":
yield from websocket.send(option)
print("> {}".format(option))
greeting = yield from websocket.recv()
print("< {}".format(greeting))
elif option == "Computer on":
yield from ws.send(option)
print("> {}".format(option))
greeting = yield from ws.recv()
print("< {}".format(greeting))
elif option == "Computer off":
yield from ws.send(option)
print("> {}".format(option))
greeting = yield from ws.recv()
print("< {}".format(greeting))
elif option == "Exit" or option == "quit":
break
else:
print("Invalid option")
finally:
print("")
yield from websocket.close()
yield from ws.close()
示例3: listen_for_event_messages
def listen_for_event_messages(self, options, loop):
attempts = 10
websocket = None
while not websocket and attempts > 0:
try:
if options['reset_mc']:
secure_client.delete_auth_tokens()
ak, ak_id = secure_client.get_auth_tokens()
ws_url = secure_client.get_websocket_url(ak, ak_id)
websocket = yield from websockets.connect(ws_url)
except Exception as e:
attempts -= 1
logger.error(e)
logger.error("Attempt failed to connect to Secure Systems websocket server")
time.sleep(1)
if not websocket:
raise Exception("Could not connect to Secure Systems websocket server.")
try:
self.is_alive = True
self.tasks.append(asyncio.ensure_future(self.alive(websocket)))
while True:
try:
message = yield from websocket.recv()
res = json.loads(message)
logger.debug("Received push message from websocket", extra={'data': res})
if res['DataType'] == 0:
process_push_data(res['Data'])
else:
logger.info("Received error from websocket", extra={'data': res})
logger.info("Restarting websocket listener")
yield from websocket.close()
secure_client.delete_auth_tokens()
ak, ak_id = secure_client.get_auth_tokens()
ws_url = secure_client.get_websocket_url(ak, ak_id)
websocket = yield from websockets.connect(ws_url)
except Exception as e:
logger.warn('ConnectionClosed %s' % e)
self.is_alive = False
break
except Exception as e:
logger.warn('Could not connect: %s' % e)
finally:
logger.warn("Importer is stopping")
if websocket:
yield from websocket.close()
self.is_alive = False
示例4: connect
def connect():
global initTime, authkey_control, endpoint_control, user_id
websocket = yield from websockets.connect(endpoint_control)
content = [22085, user_id, authkey_control]
ret = yield from messages.sendMsg(websocket, content, is_auth=True)
ret = ret.split('"id"')[0][:-1] + "}"
ret = json.loads(ret)
if ret["error"] != None:
print("CONTROL CHANNEL")
print("Error:\t", ret["error"])
print("Error - Non-None error returned!")
quit()
curTime = str(datetime.now().strftime("%H.%M.%S")) + " - " + str(datetime.now().strftime("%D"))
msg_to_send = "Bot online - Current Date/Time: {}".format(str(curTime))
ret_msg = yield from messages.sendMsg(websocket, msg_to_send)
ret_msg = json.loads(ret_msg)
yield from messages.close(websocket)
websocket = yield from websockets.connect(endpoint)
content = [channel, user_id, authkey]
ret = yield from messages.sendMsg(websocket, content, is_auth=True)
ret = ret.split('"id"')[0][:-1] + "}"
ret = json.loads(ret)
if ret["error"] != None:
print("MAIN CHANNEL")
print(ret["error"])
print("Error - Non-None error returned!")
quit()
if not args.nostartmsg:
if int(datetime.now().strftime("%H")) < 12: # It's before 12 PM - morning
timeStr = "mornin'"
elif int(datetime.now().strftime("%H")) >= 12 and int(datetime.now().strftime("%H")) < 17: # It's afternoon
timeStr = "afternoon"
elif int(datetime.now().strftime("%H")) >= 17: # It's after 5 - evening
timeStr = "evenin'"
msg_to_send = "Top o' the {} to you!".format(timeStr)
ret_msg = yield from messages.sendMsg(websocket, msg_to_send)
yield from messages.close(websocket)
else:
yield from messages.close(websocket)
示例5: hello
def hello():
websocket = ''
try:
websocket = yield from websockets.connect('ws://localhost:9000/')
except:
print("Can't initialize the connection")
i = 0
while True:
i+=1
print(i)
try:
dataJS = yield from websocket.recv()
data = json.loads(dataJS)
print("< {}".format(data))
if 'DataInfo' in data:
for val in data['DataInfo']:
logs.insert_one(val)
elif 'DataInfoReq' in data:
msg = {"DataInfo":[
{ "id":40,
"sname":"SOG",
"lname":"Speed Over Ground",
"unit":"Knts",
"min":0,
"max":99.9,
"numInstances":2,
"instanceInfo":[
{"inst":0,
"location":0,
"str":"Port"
},
{"inst":1,
"location":3,
"str":"Starboard"}]
}]}
websocket.send(msg)
elif 'export' in data:
mongoExport()
elif 'exit' in data:
break
except:
print('No Connection Available')
t.sleep(1)
# try to (re)connect
try:
websocket = yield from websockets.connect('ws://localhost:9000/')
except:
pass
yield from websocket.close()
示例6: _command
def _command(self, msg):
"""Send a command to the tv."""
logger.debug('send command to %s', "ws://{}:{}".format(self.ip, self.port));
try:
websocket = yield from websockets.connect(
"ws://{}:{}".format(self.ip, self.port), timeout=self.timeout_connect)
except:
logger.debug('command failed to connect to %s', "ws://{}:{}".format(self.ip, self.port));
return False
logger.debug('command websocket connected to %s', "ws://{}:{}".format(self.ip, self.port));
try:
yield from self._send_register_payload(websocket)
if not self.client_key:
raise PyLGTVPairException("Unable to pair")
yield from websocket.send(json.dumps(msg))
if msg['type'] == 'request':
raw_response = yield from websocket.recv()
self.last_response = json.loads(raw_response)
finally:
logger.debug('close command connection to %s', "ws://{}:{}".format(self.ip, self.port));
yield from websocket.close()
示例7: hello
def hello():
websocket = yield from websockets.connect('ws://127.0.0.1:9021/')
while True:
yield from websocket.send('all')
result = yield from websocket.recv()
print(result)
示例8: hello
async def hello():
async with websockets.connect('ws://localhost:5678') as websocket:
print("Please type username password")
q = asyncio.Queue()
asyncio.get_event_loop().add_reader(sys.stdin, got_stdin_data, q)
if len(sys.argv) == 2:
await websocket.send(sys.argv[1])
while True:
listener_task = asyncio.ensure_future(websocket.recv())
producer_task = asyncio.ensure_future(q.get())
done, pending = await asyncio.wait(
[listener_task, producer_task],
return_when=asyncio.FIRST_COMPLETED
)
if listener_task in done:
message = listener_task.result()
print("< {}".format(message))
else:
listener_task.cancel()
if producer_task in done:
raw = producer_task.result()
print("Sending {0}".format(raw))
await websocket.send(raw)
else:
producer_task.cancel()
示例9: send_message
async def send_message(msg_name, code_string):
async with websockets.connect('ws://localhost:12345') as websocket:
client_id = 4
data = code_string
await websocket.send(str(client_id) + '|' + msg_name + '|' + code_string)
print('Message sent!')
response = await websocket.recv()
a = response.split('|')
name = a[0]
if name == 'class':
print('Registered Class')
elif name == 'main':
print('Registered main')
elif name == 'run':
output = a[1]
errors = a[2]
print('Output: \n%s\n' % output)
print('Errors: \n%s\n' % errors)
else:
print(name)
asyncio.ensure_future(keep_alive_client(websocket, 1))
示例10: get_transactions
def get_transactions():
blockchain_websocket = yield from websockets.connect(BLOCKCHAIN_URL)
print("connecting to {}".format(BLOCKCHAIN_URL))
connection_text = '{"op": "unconfirmed_sub"}'
yield from blockchain_websocket.send(connection_text)
while True:
resp = yield from blockchain_websocket.recv()
resp_dict = json.loads(resp)
ip_address = resp_dict['x']['relayed_by']
amount = BLOCKCHAIN_SCALING * sum([t['value'] for t in resp_dict['x']['out']])
pprint.pprint(resp_dict)
print("IP: {0}, amount: {1} BTC".format(ip_address, amount))
location = yield from geolocate_ip(ip_address)
pprint.pprint(location)
if location['status'] != 'success':
continue
payload = dict(
lat=location['lat'],
lng=location['lon'],
amount=amount
)
pprint.pprint(payload)
for client in clients:
if client and client.open:
yield from client.send(json.dumps(payload))
示例11: websocket_to_database
def websocket_to_database():
try:
websocket = yield from websockets.connect("wss://ws-feed.exchange.coinbase.com")
except gaierror:
db_logger.error('socket.gaierror - had a problem connecting to Coinbase feed')
return
yield from websocket.send('{"type": "subscribe", "product_id": "BTC-USD"}')
while True:
message = yield from websocket.recv()
if message is None:
file_logger.error('Websocket message is None!')
break
try:
message = json.loads(message)
except TypeError:
db_logger.error('JSON did not load, see ' + str(message))
continue
if message['type'] != 'match':
continue
new_message = Messages()
for key in message:
if hasattr(new_message, key):
setattr(new_message, key, message[key])
else:
db_logger.error(str(key) + ' is missing, see ' + str(message))
continue
try:
session.add(new_message)
session.commit()
except IntegrityError:
session.rollback()
except DatabaseError:
file_logger.error('Database Error')
session.rollback()
示例12: hello
def hello():
websocket = yield from websockets.connect('ws://localhost:8765/')
name = input("What's your name? ")
yield from websocket.send(name)
print("> {}".format(name))
greeting = yield from websocket.recv()
print("< {}".format(greeting))
示例13: hello
async def hello():
async with websockets.connect('ws://localhost:8080/ws') as websocket:
while True:
data = input(">")
await websocket.send(data)
msg = await websocket.recv()
print('Message received from server:', msg)
示例14: ws_handler
def ws_handler(self, url, handler):
self.ws = yield from websockets.connect(url)
self.running = True
# Fix keepalives as long as we're ``running``.
asyncio.async(self.ws_keepalive())
while True:
content = yield from self.ws.recv()
if content is None:
break
message = json.loads(content)
if 'ok' in message:
continue
message_type = message['type']
type_handlers = self.handlers[message_type]
for handler in itertools.chain(self.handlers[ALL], type_handlers):
asyncio.async(handler(self, message))
self.running = False
示例15: query
async def query(self):
async with websockets.connect(StockUrl(account=Player.get().account, stock=Player.get().stock,
is_ticker_tape=True).str()) as websocket:
while True:
# print(json.loads(await websocket.recv()))
quote = json.loads(await websocket.recv())['quote']
await self.callback(quote)