本文整理汇总了Python中websockets.connect函数的典型用法代码示例。如果您正苦于以下问题:Python connect函数的具体用法?Python connect怎么用?Python connect使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了connect函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:dyladan,项目名称:pushbot,代码行数:32,代码来源:bot.py
示例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()
开发者ID:TedJohansson,项目名称:WebsocketNodemcu,代码行数:57,代码来源:main.py
示例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
开发者ID:dschien,项目名称:websocket_playground,代码行数:55,代码来源:import_secure.py
示例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)
开发者ID:gitter-badger,项目名称:BeamBot,代码行数:54,代码来源:beambot.py
示例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()
开发者ID:gpernelle,项目名称:RTPyLogger,代码行数:50,代码来源:client.py
示例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()
开发者ID:TheRealLink,项目名称:pylgtv,代码行数:27,代码来源:webos_client.py
示例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)
开发者ID:fgasperino,项目名称:Workflow,代码行数:7,代码来源:webevents-client.py
示例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()
开发者ID:iivvoo,项目名称:converse-server,代码行数:29,代码来源:client.py
示例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))
开发者ID:jmiron11,项目名称:csimagecode,代码行数:27,代码来源:testclient.py
示例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))
开发者ID:elvijs,项目名称:blockheads,代码行数:29,代码来源:server.py
示例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()
开发者ID:PierreRochard,项目名称:big-dipper,代码行数:34,代码来源:websocket_feed.py
示例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))
开发者ID:Ivoz,项目名称:websockets,代码行数:7,代码来源:client.py
示例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)
开发者ID:podhmo,项目名称:individual-sandbox,代码行数:7,代码来源:02websokets-client.py
示例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
开发者ID:jcarbaugh,项目名称:butterfield,代码行数:26,代码来源:core.py
示例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)
开发者ID:liux0229,项目名称:scratch,代码行数:7,代码来源:new_arch.py
示例16: hello
def hello():
websocket = yield from websockets.connect('ws://localhost:8765/')
while True:
lat_lon_amount = (yield from websocket.recv())
if lat_lon_amount:
stuff = json.loads(lat_lon_amount)
pprint.pprint(stuff)
开发者ID:elvijs,项目名称:blockheads,代码行数:7,代码来源:test_client.py
示例17: echo_ws
def echo_ws():
websocket = yield from websockets.connect('ws://localhost:8765/')
while True:
data = yield from websocket.recv()
if data is None:
break
print(data)
开发者ID:nfglynn,项目名称:eitleain,代码行数:7,代码来源:ws_listen.py
示例18: hello
def hello():
websocket = yield from websockets.connect('ws://{}:{}/'.format(HOST, PORT))
name = input("What's your name? ")
yield from websocket.send(name)
print("> {}".format(name))
greeting = yield from websocket.recv()
print("< {}".format(greeting))
开发者ID:scryver,项目名称:ilpdemo,代码行数:7,代码来源:testserver.py
示例19: mainloop
def mainloop():
ws = yield from websockets.connect('ws://localhost:8090/')
entropy = struct.unpack("<Q", os.urandom(8))[0]
rand = random.Random(entropy)
my_account_id = rand.randrange(0, 90000)
gpo_get = {"id":1, "method":"call", "params":[0, "get_objects", ["2.0.0"]]}
dgpo_sub = {"id":2, "method":"call", "params":[0, "subscribe_to_objects", [111, ["2.1.0"]]]}
acct_sub = {"id":3, "method":"call", "params":[0, "get_full_accounts", [222, ["1.2."+str(my_account_id)], True]]}
yield from ws.send(json.dumps(gpo_get))
yield from ws.send(json.dumps(dgpo_sub))
yield from ws.send(json.dumps(acct_sub))
next_call_id = 4
def peek_random_account():
nonlocal next_call_id
asyncio.get_event_loop().call_later(rand.uniform(0, 3), peek_random_account)
peek_account_id = rand.randrange(0, 90000)
acct_peek = {"id" : next_call_id, "method" : "call", "params":
[0, "get_objects", [["1.2."+str(peek_account_id)], True]]}
next_call_id += 1
yield from ws.send(json.dumps(acct_peek))
return
yield from peek_random_account()
while True:
result = yield from ws.recv()
#print(result)
if result is None:
break
yield from ws.close()
开发者ID:FollowMyVote,项目名称:graphene,代码行数:33,代码来源:api_stress.py
示例20: _ws_read
def _ws_read(self):
"""Read from websocket."""
import websockets as wslib
try:
if not self._ws:
self._ws = yield from wslib.connect(self._ws_url)
_LOGGER.info("Connected to websocket at %s", self._ws_url)
except Exception as ws_exc: # pylint: disable=broad-except
_LOGGER.error("Failed to connect to websocket: %s", ws_exc)
return
result = None
try:
result = yield from self._ws.recv()
_LOGGER.debug("Data from websocket: %s", result)
except Exception as ws_exc: # pylint: disable=broad-except
_LOGGER.error("Failed to read from websocket: %s", ws_exc)
try:
yield from self._ws.close()
finally:
self._ws = None
return result
开发者ID:lexam79,项目名称:home-assistant,代码行数:25,代码来源:spc.py
注:本文中的websockets.connect函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论