本文整理汇总了Python中websocket.create_connection函数的典型用法代码示例。如果您正苦于以下问题:Python create_connection函数的具体用法?Python create_connection怎么用?Python create_connection使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了create_connection函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: run
def run(self):
while self.terminate == False:
try:
if hasattr(self, 'ws_rs'):
del self.ws_rx
if hasattr(self, 'ws_tx'):
del self.ws_tx
self.ws_rx = websocket.create_connection('%s/receive' % self.host)
self.ws_tx = websocket.create_connection('%s/submit' % self.host)
self.send_keepalives = True
print 'connected!'
while True and not self.terminate:
msg = json.loads(self.ws_rx.recv())
if msg.get('handle') == 'FIRE':
if time.time() - int(msg.get('timestamp','0')) < MESSAGE_DISCARD_THRESHOLD:
self.squirtgun.pulse(float(msg.get('text', '0.5')))
except websocket.WebSocketConnectionClosedException, e:
print 'connection closed'
self.send_keepalives = False
except socket.error, e:
if e.errno == 61:
print 'connection refused'
else:
print 'socket error number %d' % e.errno
self.send_keepalives = False
开发者ID:crdunwel,项目名称:raspi_squirtgun,代码行数:27,代码来源:run.py
示例2: test_forbidden_channel
def test_forbidden_channel(self):
websocket_url = self.websocket_base_url + u'?subscribe-broadcast&publish-broadcast'
try:
create_connection(websocket_url, header=['Deny-Channels: YES'])
self.fail('Did not reject channels')
except WebSocketException:
self.assertTrue(True)
开发者ID:strayiker,项目名称:django-websocket-redis,代码行数:7,代码来源:test_chatclient.py
示例3: main
def main():
ws = create_connection("ws://88.198.19.60:9001/")
tw_client = get_twitter_client()
current_state = 0
counter = 0
last_tweet_time = 0
while True:
try:
data = get_socket_data(ws, 'Parrulaituri', 'Analog Sensor Data', 'Soil moisture')
# data = get_socket_data(ws, 'Light Sensor Data', 'Illuminance')
# data = get_socket_data(ws, 'Parrulaituri', 'Barometer Sensor Data', 'Temperature')
value = data.get(u'value')
if value is None:
continue
tweet, current_state = get_tweet(value, current_state, last_tweet_time)
logger.debug(tweet, current_state, value)
if tweet is not None:
tw_client.statuses.update(status=tweet)
last_tweet_time = time.time()
except Exception as e:
logger.exception(e)
ws = create_connection("ws://88.198.19.60:9001/")
tw_client = get_twitter_client()
counter += 1
if counter > 300:
break
开发者ID:jokallun,项目名称:flow-talks,代码行数:27,代码来源:tweets.py
示例4: init_websocket
def init_websocket():
try:
GlobalVars.metasmoke_ws = websocket.create_connection(
GlobalVars.metasmoke_ws_host, origin=GlobalVars.metasmoke_host
)
payload = json.dumps(
{
"command": "subscribe",
"identifier": '{"channel":"SmokeDetectorChannel",' '"key":"' + GlobalVars.metasmoke_key + '"}',
}
)
GlobalVars.metasmoke_ws.send(payload)
while True:
a = GlobalVars.metasmoke_ws.recv()
try:
data = json.loads(a)
Metasmoke.handle_websocket_data(data)
except Exception, e:
GlobalVars.metasmoke_ws = websocket.create_connection(
GlobalVars.metasmoke_ws_host, origin=GlobalVars.metasmoke_host
)
payload = json.dumps({"command": "subscribe", "identifier": '{"channel":"SmokeDetectorChannel"}'})
GlobalVars.metasmoke_ws.send(payload)
print e
try:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
except:
print "meh"
except:
print "Couldn't bind to MS websocket"
开发者ID:Charcoal-SE,项目名称:SmokeDetector,代码行数:32,代码来源:metasmoke.py
示例5: WebSocketConnection
def WebSocketConnection(self):
if not self.verify_cert:
self.ws = None
self.ws = create_connection(self.url, enable_multithread=True,
sslopt={"cert_reqs": ssl.CERT_NONE})
else:
self.ws = None
if self.identity is not None:
if self.identity.root_ca_cert:
if not (os.path.exists(self.identity.root_ca_cert)):
log.error("Error : Wrong CA certificate path.")
raise ValueError("Error : Wrong CA certificate path.")
else:
log.error("Error : CA certificate path is missing")
raise ValueError("Error : CA certificate path is missing")
if os.path.isfile(self.identity.root_ca_cert):
try:
self.ws = create_connection(self.url, enable_multithread=True,
sslopt={"cert_reqs": ssl.CERT_REQUIRED,
"ca_certs": self.identity.root_ca_cert})
except ssl.SSLError:
log.exception("SSL Error during Websocket connection.")
raise Exception("SSL Error during Websocket connection.")
else:
log.error("Identity object is missing")
raise ValueError("Identity object is missing")
if self.ws is None:
raise (IOError("Couldn't verify host certificate"))
开发者ID:JonghoWon,项目名称:liota,代码行数:28,代码来源:web_socket.py
示例6: __init__
def __init__(self, url, timeout=10):
if not url.endswith('/'):
url+='/'
# POST or GET <url>/kernel
# if there is a terms of service agreement, you need to
# indicate acceptance in the data parameter below (see the API docs)
reply = requests.post(
url+'kernel',
data={'accepted_tos':'true'},
headers={'Accept': 'application/json'},
)
# Subsequent connections (including websocket) must preserve
# the cookies for the backend to route to the right server
cookie = ''
for key, value in reply.cookies.items():
cookie += '{0}={1}; '.format(key, value)
# RESPONSE: {"id": "ce20fada-f757-45e5-92fa-05e952dd9c87", "ws_url": "ws://localhost:8888/"}
# construct the iopub and shell websocket channel urls from that
response = reply.json()
self.kernel_url = response['ws_url']+'kernel/'+response['id']+'/'
websocket.setdefaulttimeout(timeout)
print self.kernel_url
self._shell = websocket.create_connection(self.kernel_url+'shell', cookie=cookie)
self._iopub = websocket.create_connection(self.kernel_url+'iopub', cookie=cookie)
# initialize our list of messages
self.shell_messages = []
self.iopub_messages = []
开发者ID:Abramovuch,项目名称:sagecell,代码行数:32,代码来源:sagecell-client.py
示例7: test_reuseSessionId
def test_reuseSessionId(self):
on_close = lambda(ws): self.assertFalse(True)
ws_url = 'ws:' + base_url.split(':',1)[1] + \
'/000/' + str(uuid.uuid4()) + '/websocket'
ws1 = websocket.create_connection(ws_url, on_close=on_close)
self.assertEqual(ws1.recv(), u'o')
ws2 = websocket.create_connection(ws_url, on_close=on_close)
self.assertEqual(ws2.recv(), u'o')
ws1.send(u'"a"')
self.assertEqual(ws1.recv(), u'a["a"]')
ws2.send(u'"b"')
self.assertEqual(ws2.recv(), u'a["b"]')
ws1.close()
ws2.close()
# It is correct to reuse the same `session_id` after closing a
# previous connection.
ws1 = websocket.create_connection(ws_url)
self.assertEqual(ws1.recv(), u'o')
ws1.send(u'"a"')
self.assertEqual(ws1.recv(), u'a["a"]')
ws1.close()
开发者ID:AhmedSoliman,项目名称:sockjs-protocol,代码行数:27,代码来源:sockjs-protocol-0.1.py
示例8: ServerWait
def ServerWait():
ws = create_connection(SOCKET_CONNECTION_URL)
# When program starts, open a connection and send a websocket packet to server with following command
# IMPORTANT: whisper_id is a pre-existing number associated with already-created whispers on the server,
# so send me something that i have sent you already...
message = {"pi_incoming_username": PI_USERNAME}
message_str = json.dumps(message)
print "Sending " + message_str
ws.send(message_str)
while True:
try:
result = ws.recv()
print "Received '%s'" % result
json_object = json.loads(result)
whisper_id = json_object['whisper_id']
PostRequest(whisper_id)
except KeyboardInterrupt:
exit()
break
except Exception, e:
print e.message
print "Reconnecting in 30 seconds.."
time.sleep(10)
ws = create_connection(SOCKET_CONNECTION_URL)
ws.send(message_str)
print("[SOCKET] " + PI_USERNAME + " connection restablished...")
开发者ID:delvinv,项目名称:illumi-server,代码行数:28,代码来源:Howard_code.py
示例9: test_client
def test_client(self):
# websocket.enableTrace(True)
ws = websocket.create_connection("ws://127.0.0.1:8888/talk/chat/room_hipo/?token=TOKEN_1234")
# TODO: wait until authorization
time.sleep(2)
d = json.dumps(dict(
body="hello world",
type="message"
))
ws.send(d)
d = json.dumps(dict(
body="hello 2222",
type="message"
))
ws.send(d)
result = ws.recv()
print "result --- ", result
ws.close()
resp = requests.get(
'http://127.0.0.1:8888/talk/history/room_hipo,room_foo?token=TOKEN_1234'
)
data = json.loads(resp.content)
self.assertEquals(data['results'][0]['messages'][0]["body"], "hello 2222")
self.assertEquals(len(data['results'][1]["messages"]), 0)
ws = websocket.create_connection("ws://127.0.0.1:8888/talk/chat/room_hipo/?token=TOKEN_5555")
time.sleep(5)
d = json.dumps(dict(
body="hello world 3333",
type="message"
))
ws.send(d)
d = json.dumps(dict(
body="hello 4444",
type="message"
))
ws.send(d)
ws.close()
resp = requests.get(
'http://127.0.0.1:8888/talk/old/room_hipo?token=TOKEN_1234'
)
data = json.loads(resp.content)
print "================================"
print "un......"
print data['results']['unread_messages'][0]
print "================================"
self.assertEquals(data['results']['read_messages'][0]["body"], "hello 2222")
self.assertEquals(data['results']['unread_messages'][0]["body"], "hello 4444")
开发者ID:Hipo,项目名称:hipochat,代码行数:59,代码来源:test-chat.py
示例10: test_asgi_ws_order_0
def test_asgi_ws_order_0(site, asgi):
# websocket.connect['order'] should always be 0
ws1 = create_connection(site.ws_url, timeout=2)
asgi_connect1 = asgi.receive_ws_connect()
assert asgi_connect1['order'] == 0
ws2 = create_connection(site.ws_url, timeout=2)
asgi_connect2 = asgi.receive_ws_connect()
assert asgi_connect2['order'] == 0
开发者ID:mjkillough,项目名称:iis-asgi-handler,代码行数:8,代码来源:test_asgi_ws.py
示例11: __init__
def __init__(self, ph):
pubport = ":1990"
hunterport = ":1991"
preyport = ":1992"
host = "ws://localhost"
self.ph = ph
self.pubsocket = create_connection(host + pubport)
self.phsocket = create_connection(host + (preyport if ph == 'p' else hunterport))
开发者ID:torypeterschild,项目名称:evasion,代码行数:8,代码来源:evinterface.py
示例12: run
def run():
from websocket import create_connection
uri = 'ws://%s:%s/:/websockets/notifications' % (
plexcs.CONFIG.PMS_IP,
plexcs.CONFIG.PMS_PORT
)
# Set authentication token (if one is available)
if plexcs.CONFIG.PMS_TOKEN:
uri += '?X-Plex-Token=' + plexcs.CONFIG.PMS_TOKEN
ws_connected = False
reconnects = 0
# Try an open the websocket connection - if it fails after 15 retries fallback to polling
while not ws_connected and reconnects <= 15:
try:
logger.info(u'Plex:CS WebSocket :: Opening websocket, connection attempt %s.' % str(reconnects + 1))
ws = create_connection(uri)
reconnects = 0
ws_connected = True
logger.info(u'Plex:CS WebSocket :: Ready')
except IOError as e:
logger.error(u'Plex:CS WebSocket :: %s.' % e)
reconnects += 1
time.sleep(5)
while ws_connected:
try:
process(*receive(ws))
# successfully received data, reset reconnects counter
reconnects = 0
except websocket.WebSocketConnectionClosedException:
if reconnects <= 15:
reconnects += 1
# Sleep 5 between connection attempts
if reconnects > 1:
time.sleep(5)
logger.warn(u'Plex:CS WebSocket :: Connection has closed, reconnecting...')
try:
ws = create_connection(uri)
except IOError as e:
logger.info(u'Plex:CS WebSocket :: %s.' % e)
else:
ws_connected = False
break
if not ws_connected:
logger.error(u'Plex:CS WebSocket :: Connection unavailable, falling back to polling.')
plexcs.POLLING_FAILOVER = True
plexcs.initialize_scheduler()
logger.debug(u'Plex:CS WebSocket :: Leaving thread.')
开发者ID:zobe123,项目名称:Plex-CS,代码行数:58,代码来源:web_socket.py
示例13: test
def test():
log_debug('register', 'start testing ')
get_pkgs_details_cnt = 0
for i in range(TEST_ROUNDS):
if SHOW_TIME:
start_time = datetime.utcnow()
if RANDOM_CAT:
cat_num = randint(0, len(CAT) - 1)
cat_name = CAT[cat_num]
if not CATEGORIES.has_key(cat_name):
log_err('get_packages_details', 'failed to get the category, invalid category is %s' % str(cat_name))
return False
cate = CATEGORIES[cat_name]
else:
cate = CATEGORY
message = json.dumps({'operator':'get_counter', 'category':cate})
ws = create_connection("ws://%s:%d/" % (get_manager(), get_port()))
ws.send(message)
ret = ws.recv()
ws.close()
result = json.loads(ret)
if not result or 'get_counter' != result['operator'] or cate != result['category'] or not result['data']:
log_err('get_counter', 'failed to get counter')
return False
counter = result['data']
if not counter:
log_err('get_counter', 'failed to get the total number of %s ' % str(cate))
return False
if SHOW_TIME:
log_debug('get_counter', 'time=%d sec' % (datetime.utcnow() - start_time).seconds)
log_debug('get_counter', 'counter=%s' % str(counter))
rank = randint(0, (int(counter) + PAGE_SIZE - 1) / PAGE_SIZE - 1)
log_debug('get_counter', 'rank=%d' % rank)
if SHOW_TIME:
start_time = datetime.utcnow()
message = json.dumps({'operator':'get_packages_details', 'category':cate, 'rank':rank})
ws = create_connection("ws://%s:%d/" % (get_manager(), get_port()))
ws.send(message)
ret = ws.recv()
ws.close()
result = json.loads(ret)
if not result or 'get_packages_details' != result['operator'] or cate != result['category'] or rank != result['rank'] or not result['data']:
log_err('get_packages_details', 'failed to get packages details')
return False
ret = result['data']
for item in ret:
if not item['pkg'] or not item['title'] or not item['auth']:
log_err('get_packages_details', 'failed to get valid details')
return False
if SHOW_TIME:
log_debug('get_packages_details', 'time=%d sec' % (datetime.utcnow() - start_time).seconds)
get_pkgs_details_cnt += 1
log_debug('get_packages_details', 'get_pkgs_details_cnt=%d' % get_pkgs_details_cnt)
log_debug('get_packages_details', 'packages_details=%s' % str(ret))
开发者ID:tx626,项目名称:dpmtest,代码行数:57,代码来源:getpackagesdetails.py
示例14: __init__
def __init__(self):
f = urllib2.urlopen("%s/kernel" % (root,), "")
data = json.loads(f.read())
f.close()
self.kernel_id = data["kernel_id"]
self.ws_url = data["ws_url"]
self.iopub = websocket.create_connection("%skernel/%s/iopub" % (self.ws_url, self.kernel_id))
self.shell = websocket.create_connection("%skernel/%s/shell" % (self.ws_url, self.kernel_id))
self.session_id = str(uuid.uuid4())
开发者ID:Abramovuch,项目名称:sagecell,代码行数:9,代码来源:client.py
示例15: test_host_api_garbage_token
def test_host_api_garbage_token(client):
hosts = client.list_host(kind='docker', removed_null=True)
assert len(hosts) > 0
# pass garbage token
stats = hosts[0].stats()
with pytest.raises(Exception) as excinfo:
ws.create_connection(stats.url+'?token=abcd')
assert 'Handshake status 401' in str(excinfo.value)
开发者ID:galal-hussein,项目名称:validation-tests,代码行数:9,代码来源:test_host_api.py
示例16: connect_targetID
def connect_targetID(self, targetID):
try:
wsurl = 'ws://{}:{}/devtools/page/{}'.format(self.host, self.port, targetID)
self.close()
self.ws = websocket.create_connection(wsurl)
self.ws.settimeout(self.timeout)
except:
wsurl = self.tabs[0]['webSocketDebuggerUrl']
self.ws = websocket.create_connection(wsurl)
self.ws.settimeout(self.timeout)
开发者ID:katrid,项目名称:orun,代码行数:10,代码来源:client.py
示例17: main
def main():
"""docstring for main"""
publisher = websocket.create_connection("ws://localhost:1990")
if sys.argv[1] == "H":
role = "H"
port = "1991"
url = "ws://localhost:" + port
ws = websocket.create_connection(url)
# prey = websocket.create_connection("ws://localhost:1992")
else:
role = 'P'
port = "1992"
url = "ws://localhost:" + port
ws = websocket.create_connection(url)
# hunter = websocket.create_connection("ws://localhost:1991")
print "%s, Welcome!" % role
test = None
while True:
times = 1
if role == "H":
times = 2
for i in range(times):
a = raw_input("command >")
pack = {}
if a == "B":
wall_length = raw_input("wall_lenth >")
wall_direct = raw_input("wall direction >")
pack = {"command": "B", "wall": {"length": wall_length,
"direction": wall_direct}}
elif a == "D":
wall_index = raw_input("wall index>")
pack = {"command": "D", "wallindex": wall_index}
elif a == "M":
if role == "P":
direction = raw_input("move direction>")
pack = {"command": "M", "direction": direction}
else:
pack = {"command": "M"}
elif a == "P":
pack = {"command": "P"}
elif a == "W":
pack = {"command": "W"}
else:
print "unknown command"
continue
json_string = json.dumps(pack)
print "==|| message sent: %s" % json_string
ws.send(json_string)
test = 1
if a == "P" or a == "W":
result = ws.recv()
print "==|| Get message: %s" % result
开发者ID:yucheng1992,项目名称:Heuristic-problem-solving,代码行数:55,代码来源:echo_client.py
示例18: __init__
def __init__(self):
domain = raw_input('Enter server address(enter blank for default)')
print('connecting to server....')
if domain:
self.ws = websocket.create_connection(domain)
else:
self.ws = websocket.create_connection('ws://py2pyrpc.herokuapp.com/')
print('waking up server....')
time.sleep(3)
print(self.ws.recv())
thread.start_new_thread(self.pinger,(),)
开发者ID:ishankhare07,项目名称:rpc,代码行数:11,代码来源:client.py
示例19: __init__
def __init__(self):
self.__token = self.get_token()
self.__closeConnectionOnError = False
self.script_path = customConfig.websocket_url + "/" + self.get_token()
self.__subscribe_message_id = None
self.callback_map = customConfig.callback_map
websocket.enableTrace(True)
self.__subscribe_unsubscribe_ws = create_connection(self.script_path)
sub_unsub_count = 0
#First we have to check if the websocket is connected
#if it's not connected we will attempt to connect up to 10 times
if not self.__subscribe_unsubscribe_ws.connected and sub_unsub_count < 10:
while not self.__subscribe_unsubscribe_ws.connected:
sub_unsub_count += 1
self.__subscribe_unsubscribe_ws = create_connection(self.script_path)
elif sub_unsub_count > 10 and not self.__subscribe_unsubscribe_ws.connected:
logging.exception("Connection to scriptr via websocket couldn't be established.")
#same as the previous websocket connection
pub_count = 0
self.__publish_ws = create_connection(self.script_path)
if not self.__publish_ws.connected and pub_count < 10:
while not self.__publish_ws.connected:
pub_count += 1
self.__publish_ws = create_connection(self.script_path)
elif pub_count > 10 and not self.__publish_ws.connected:
logging.exception("Connection to scriptr via websocket couldn't be established.")
# Function executed from threads that listens to the websockets responses
def __listen(ws, message, **args):
while ws.connected:
listen_result = ws.recv()
message = listen_result
print(message)
if (self.__subscribe_message_id and message == "sub_unsub"):
for i in range(0, len(self.get_callback_map[self.__subscribe_message_id])):
callback_function = self.get_callback_map[self.__subscribe_message_id][i]
callback_function(message)
if (self.get_close_connection_flag()):
ws.close()
# create two threads that handles the websocket connections.
try:
process_sub_unsub_thread = threading.Thread(target=__listen,
args=[self.__subscribe_unsubscribe_ws, "sub_unsub"])
process_sub_unsub_thread.start()
except threading.TIMEOUT_MAX as e:
logging.exception("An error with a thread has occurred!")
try:
process_pub_thread = threading.Thread(target=__listen, args=[self.__publish_ws, "publish"])
process_pub_thread.start()
except threading.TIMEOUT_MAX as e:
logging.exception("An error with a thread has occurred!")
开发者ID:scriptrdotio,项目名称:libraries,代码行数:54,代码来源:scriptr_client.py
示例20: execute
def execute(self, code):
r = urllib.request.urlopen(self.req)
d = json.loads(r.read().decode('utf-8'))
self.kernel_url = '{}kernel/{}/'.format(d['ws_url'], d['kernel_id'])
logging.debug(self.kernel_url)
_shell = websocket.create_connection(self.kernel_url + 'shell')
_iopub = websocket.create_connection(self.kernel_url + 'iopub')
_shell.send(self._make_execute_request(code))
msg_list = self._get_iopub_messages(_iopub)
#msg_list = self._get_shell_messages(self._shell)
_shell.close()
_iopub.close()
return msg_list
开发者ID:shikil,项目名称:PyInterpreter,代码行数:13,代码来源:sage.py
注:本文中的websocket.create_connection函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论