本文整理汇总了Python中socketIO_client.SocketIO.disconnect方法的典型用法代码示例。如果您正苦于以下问题:Python SocketIO.disconnect方法的具体用法?Python SocketIO.disconnect怎么用?Python SocketIO.disconnect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socketIO_client.SocketIO
的用法示例。
在下文中一共展示了SocketIO.disconnect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: YetiSocket
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class YetiSocket():
def __init__(self, host='localhost', port=5001):
self.io = SocketIO(host, port)
self.cam = self.io.define(CamNamespace, '/cam')
self.cam.on('config_update', self.config_update)
self.cam.on('manual_capture', self.manual_capture)
self._thread = threading.Thread(target=self.io.wait)
self._thread.daemon = True
self._thread.start()
def send(self, event, data):
self.cam.emit(event, data)
def config_update(self, data):
print 'config update: %s' % data
def manual_capture(self, data):
print 'manual capture: ' + data
def connect(self):
self.cam.connect()
def disconnect(self):
self.cam.disconnect()
self.io.disconnect()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.disconnect()
示例2: __init__
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class LoveSocket:
def __init__(self):
self.io = None
self.hearts = 0
self.poos = 0
def start(self):
threading.Thread(target=self.__start).start()
def __start(self):
self.io = SocketIO(LOVE_SOCKET_URL, verify=False)
self.io.on("love", self.__add_love)
self.io.on("poo", self.__add_poo)
self.io.wait()
def stop(self):
self.io.disconnect()
self.io = None
def reset_hearts(self):
hearts = self.hearts
self.hearts = 0
return hearts
def reset_poos(self):
poos = self.poos
self.poos = 0
return poos
def __add_love(self, *args):
self.hearts += 1
def __add_poo(self, *args):
self.poos += 1
示例3: DocumentSyncTest
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class DocumentSyncTest(BaseTestCase):
def setUp(self):
super(DocumentSyncTest, self).setUp()
self.client = SocketIO('localhost', config.SERVER_PORT, DocumentNamespace)
self.doc = self.client.define(DocumentNamespace, DOCUMENT_NAMESPACE)
global RECEIVED
RECEIVED = {}
def tearDown(self):
super(DocumentSyncTest, self).tearDown()
self.client.disconnect()
def test_echo(self):
self.doc.on('echo', on_echo_response)
self.doc.emit('echo', 'hello world')
self.client.wait(seconds=1)
self.assertTrue(RECEIVED.get('on_echo_response', False))
def test_single_client(self):
self.doc.on('userlist', on_userlist_response)
self.doc.on('document', on_document_response)
self.doc.emit('join', {'username': 'Florian', 'document': DOCUMENT_ID})
self.client.wait(seconds=1)
self.doc.emit('leave', {'username': 'Florian', 'document': DOCUMENT_ID})
self.assertTrue(RECEIVED.get('on_userlist_response', False))
self.assertTrue(RECEIVED.get('on_document_response', False))
示例4: SocketIOHandler
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class SocketIOHandler(object):
def __init__(self, cfg):
"""
save the server config..
"""
self.server_address = cfg['graphite_ip']
self.server_port = cfg['graphite_port']
self.namespace = cfg['graphite_namespace']
self.socketIO = None
self.channel = None
def handle(self, non_metrics):
if len(non_metrics) == 0:
logging.debug('No metrics be handled!')
return
nm_list = []
for nm in non_metrics:
nm_list.append(dumps(nm.to_dict())) # serialized to json
msg_type = non_metrics[0].type
self.socketIO = SocketIO(self.server_address, self.server_port, BaseNamespace)
self.channel = self.socketIO.connect(self.namespace, BaseNamespace)
self.channel.emit(msg_type, nm_list, self.on_response) # send to server
self.socketIO.wait(forCallbacks=True)
logging.debug('SokcetIOHandler emitting %s to sever:\n %s' % (msg_type, dumps(nm_list)))
def on_response(self, *args):
# is it necessary?
self.socketIO.disconnect()
logging.debug('emit non metrics success!')
示例5: ices_get_next
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
def ices_get_next():
global io, file, HOST, PORT, STATION, TOKEN
io = SocketIO(HOST, PORT, Namespace)
io.emit('next', { 'station': STATION, 'token': TOKEN })
io.wait(seconds=1)
io.disconnect()
path = file.encode('utf8') # Path to audio file, must be of 'str' type (not 'unicode'), e.g. "/music/Beatles - Yesterday.mp3"
file = '' # Clear so it wont repeat in case the 'next' callback timeouts
return path
示例6: CanvasClient
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class CanvasClient(object):
def __init__(self, options):
self.name = options["name"]
self.moduleName = options["moduleName"]
self.className = options["className"]
if not self.className:
raise Exception("Must give python modules a class name in options")
self.serverIP = options["serverIP"]
self.serverPort = options["serverPort"]
self.options = options
module = importlib.import_module("modules.%s" % self.moduleName)
klass = getattr(module, self.className)
self.module = klass(self, self.options)
self.socket = None
def connect(self):
self.socketIO = SocketIO(self.serverIP, self.serverPort)
self.socketIO.on('event', self.onEvent)
self.socketIO.on('action', self.onAction)
self.socketIO.wait()
def disconnect(self):
self.socketIO.disconnect()
def onEvent(self, message):
print "%s %s %s" % (self.name, "onEvent", message)
self.module.onEvent(message)
sys.stdout.flush()
def onAction(self, message):
print "%s %s %s" % (self.name, "onAction", message)
if "to" in message and message["to"] == self.name:
self.module.onAction(message)
sys.stdout.flush()
def emitEvent(self, event, eventData):
message = {
"from": self.name,
"event": event,
"data": eventData
}
print "%s %s %s" % (self.name, "emitEvent", message)
self.socketIO.emit("event", message)
sys.stdout.flush()
def emitAction(self, to, action, data):
message = {
"from": self.name,
"to": to,
"action": action,
"data": data
}
print "%s %s %s" % (self.name, "emitAction", message)
self.socketIO.emit("action", message)
sys.stdout.flush()
示例7: ices_init
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
def ices_init():
global io, alive, HOST, PORT, STATION, TOKEN
io = SocketIO(HOST, PORT, Namespace)
io.emit('alive', { 'station': STATION, 'token': TOKEN })
io.wait(seconds=1)
io.disconnect()
if alive:
return 1 # Succees
else:
return 0 # Failure
示例8: __init__
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class Connection:
def __init__(self, application, server, port):
self.application = application
self.server = server
self.port = port
self.connection_opened = False
self.trip_started = False
self.trip_id = None
#self.open_connection()
def send_data(self, data):
to_send = {'_id':self.trip_id, "sensorData":data}
print("tries to send: ",to_send)
self.socket.emit('rt-sensordata', json.dumps(to_send))
def open_connection(self):
self.socket = SocketIO(self.server, self.port)
self.socket.on('server_message', self.on_response)
self.connection_opened = True
self.thread = threading.Thread(name='connection', target=self.action)
self.thread.start()
def close_connection(self):
self.socket.disconnect()
def start_trip(self):
data = {'purpose':'realtime-sender', 'groupID':self.application.group_id, 'userID':self.application.user_id}
self.socket.emit('start', json.dumps(data))
def stop_trip(self):
data = {'_id':self.trip_id, "meta":None}
self.socket.emit('endBikeTrip', json.dumps(data))
self.trip_started = False
def live_trip_active(self):
return self.connection_opened and self.trip_started
def on_response(self, *args):
parsed = args[0]
print "received data:",args[0]
if "Connection accepted. Ready to receive realtime data." in parsed:
self.trip_started = True
self.trip_id = parsed['_id']
print("trip started, id = ", self.trip_id)
elif "bikeTrip saved to Database" in parsed:
self.trip_started = False
print("trip saved to database!")
elif "illegal JSON data received" in parsed:
print("saving data to database failed")
elif u'Welcome' in parsed:
print("Welcome! ", parsed)
else:
print("error: ",parsed)
def action(self):
while self.socket.connected:
self.wait()
def wait(self):
self.application.send_data()
time.sleep(.2)
self.socket.wait(.5)
示例9: AtlasStream
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class AtlasStream(object):
CHANNEL_RESULT = "atlas_result"
CHANNEL_PROBE = "atlas_probe"
CHANNEL_ERROR = "atlas_error"
CHANNELS = {"result": CHANNEL_RESULT, "probe": CHANNEL_PROBE, "error": CHANNEL_ERROR}
def __init__(self, **kwargs):
"""Initialize stream"""
self.iosocket_server = "atlas-stream.ripe.net"
self.iosocket_resource = "/stream/socket.io"
self.socketIO = None
def connect(self):
"""Initiate the channel we want to start streams from."""
self.socketIO = SocketIO(
host=self.iosocket_server, port=80, resource=self.iosocket_resource, transports=["websocket"]
)
def disconnect(self):
"""Exits the channel k shuts down connection."""
self.socketIO.disconnect()
self.socketIO.__exit__([])
def bind_stream(self, stream_type, callback):
"""Bind given type stream with the given callback"""
try:
self.socketIO.on(self.CHANNELS[stream_type], callback)
except KeyError:
print "The given stream type: <{}> is not valid".format(stream_type)
def start_stream(self, stream_type, **stream_parameters):
"""Starts new stream for given type with given parameters"""
if stream_type in ("result", "probestatus"):
self.subscribe(stream_type, **stream_parameters)
else:
print "Given stream type: <%s> is not valid" % stream_type
def subscribe(self, stream_type, **parameters):
"""Subscribe to stream with give parameters."""
parameters.update({"stream_type": stream_type})
self.socketIO.emit("atlas_subscribe", parameters)
def timeout(self, seconds=None):
"""
Times out all streams after n seconds or wait forever if seconds is
None
"""
if seconds is None:
self.socketIO.wait()
else:
self.socketIO.wait(seconds=seconds)
示例10: EtherpadIO
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class EtherpadIO(object):
def __init__(self, pad, cb,
host='localhost', path='p/', port='9001', secure=False,
verbose = False,
transports=['xhr-polling', 'websocket'],
**kwarg):
log.debug('EtherpadIO(%s://%s:%s/%s%s")' % ('https' if secure else 'http', host,
port, path, pad))
res = requests.get("%s://%s:%s/%s%s" % ('https' if secure else 'http',
host, port, path, pad))
cookie = res.headers['set-cookie']
self.cookie = dict([(cookie[:cookie.find("=")], cookie[cookie.find("=")+1:])])
self.pad = pad
self.cb = cb
self.host = host
self.path = path
self.port = port
self.secure = secure
self.kwarg = kwarg
self.transports = transports
self.__init()
def __init(self):
self.epad = SocketIO(self.host, self.port,
EtherpadService,
secure=self.secure,
transports=self.transports,
cookies=self.cookie,
padid=self.pad,
cb=self.cb, **self.kwarg)
def wait(self):
reconnect = True
while reconnect:
reconnect = self.epad.wait()
del self.epad
if reconnect:
self.__init()
def has_ended(self):
return self.epad.has_ended()
def stop(self):
self.epad.disconnect()
def pause(self):
self.epad.pause()
def patch_text(self, old, new):
cs = pack(old.diff(new))
if cs:
self.epad.namespace.send_user_changes(old.get_revision(), old.get_apool(), cs)
示例11: __init__
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class YetiSocket:
def __init__(self, host='localhost', port=5001, config_update_callback=None, manual_capture_callback=None):
self._thread = threading.Thread(target=self._worker, args=(host, port, config_update_callback, manual_capture_callback))
self._thread.daemon = True
self._thread.start()
def _worker(self, host, port, config_update_callback, manual_capture_callback):
self.io = SocketIO(host, port)
self.cam = self.io.define(LoggingNamespace, '/cam')
if config_update_callback:
self.cam.on('config_update', config_update_callback)
if manual_capture_callback:
self.cam.on('manual_capture', manual_capture_callback)
self.io.wait()
def alert(self, data):
logger.info("Sending alert to server: %s" % data)
self.cam.emit("alert", data)
def config_updated(self, status):
logger.info("Sending config updated result: %s" % status)
self.cam.emit("config_updated", {"status":status})
def manual_capture_result(self, result):
logger.info("Sending manual capture result: %s" % result)
self.cam.emit("manual_capture_result", {"result":result})
def connect(self):
self.cam.connect()
def disconnect(self):
self.cam.disconnect()
self.io.disconnect()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.disconnect()
示例12: simulate_sa_alarm
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
def simulate_sa_alarm(alarm, delay, cont):
cont += 1
time.sleep(delay)
cursor = connection.cursor()
sql = "insert into alarms_alarmevents (alarm_id, triggered_time, value) " \
"values (%s, %s, %s)"
triggered_time = str(datetime.datetime.utcnow())
cursor.execute(sql, [alarm.pk, str(triggered_time), 300])
transaction.commit_unless_managed()
cursor.execute("SELECT id FROM alarms_alarmevents WHERE "
"triggered_time = %s AND alarm_id = %s",
[triggered_time, alarm.pk])
row = cursor.fetchone()
alarm_event = row[0]
socket = SocketIO('auditem.mx', 9999)
socket.emit('alarm_trigger', {'alarm_event': alarm_event})
print "alarm ", alarm.pk, "triggered at", triggered_time
sql = "insert into alarms_alarmevents (alarm_id, triggered_time, value) " \
"values (%s, %s, %s)"
triggered_time = str(datetime.datetime.utcnow())
cursor.execute(sql, [alarm.pk, str(triggered_time), 300])
transaction.commit_unless_managed()
cursor.execute("SELECT id FROM alarms_alarmevents WHERE "
"triggered_time = %s AND alarm_id = %s",
[triggered_time, alarm.pk])
row = cursor.fetchone()
alarm_event = row[0]
socket.emit('alarm_trigger', {'alarm_event': alarm_event})
SocketIO.disconnect(socket)
print "alarm ", alarm.pk, "triggered at", triggered_time
if cont < 60:
simulate_sa_alarm(alarm, 30, cont)
else:
print "Simulation complete"
return
示例13: WebLights
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class WebLights(threading.Thread):
class WebLightsNamespace(BaseNamespace):
def on_connect(self):
print '[Connected]'
log.info("Connected to weblights")
def on_dc_lights(self, status):
log.info("dc_lights_update: " + str(status))
def on_keep_alive(self, *args):
log.debug("Received keep_alive")
def run(self):
log.info("Starting weblights")
self.socketIO = SocketIO(
cowtv_config["weblights"],
Namespace=self.WebLightsNamespace)
self.socketIO.wait()
def toggle(self):
self.socketIO.emit("toggle_lights")
def disconnect(self):
self.socketIO.disconnect()
示例14: AtlasStream
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
class AtlasStream(object):
EVENT_NAME_RESULTS = "atlas_result"
EVENT_NAME_SUBSCRIBE = "atlas_subscribe"
EVENT_NAME_ERROR = "atlas_error"
# Remove the following list when deprecation time expires
CHANNELS = {
"result": "atlas_result",
"probe": "atlas_probestatus",
"error": "atlas_error",
}
# -------------------------------------------------------
def __init__(self, debug=False, server=False, proxies=None, headers=None):
"""Initialize stream"""
self.iosocket_server = "atlas-stream.ripe.net"
self.iosocket_resource = "/stream/socket.io"
self.socketIO = None
self.debug = debug
self.error_callback = None
self.proxies = proxies or {}
self.headers = headers or {}
if not self.headers or not self.headers.get("User-Agent", None):
user_agent = "RIPE ATLAS Cousteau v{0}".format(__version__)
self.headers["User-Agent"] = user_agent
if self.debug and server:
self.iosocket_server = server
def handle_error(self, error):
if self.error_callback is not None:
self.error_callback(error)
else:
print(error)
def connect(self):
"""Initiate the channel we want to start streams from."""
self.socketIO = SocketIO(
host=self.iosocket_server,
port=80,
resource=self.iosocket_resource,
proxies=self.proxies,
headers=self.headers,
transports=["websocket"],
Namespace=AtlasNamespace,
)
self.socketIO.on(self.EVENT_NAME_ERROR, self.handle_error)
def disconnect(self):
"""Exits the channel k shuts down connection."""
self.socketIO.disconnect()
self.socketIO.__exit__([])
def unpack_results(self, callback, data):
if isinstance(data, list):
for result in data:
callback(result)
else:
callback(data)
def bind_channel(self, channel, callback):
"""Bind given channel with the given callback"""
# Remove the following list when deprecation time expires
if channel in self.CHANNELS:
warning = (
"The event name '{}' will soon be deprecated. Use "
"the real event name '{}' instead."
).format(channel, self.CHANNELS[channel])
self.handle_error(warning)
channel = self.CHANNELS[channel]
# -------------------------------------------------------
if channel == self.EVENT_NAME_ERROR:
self.error_callback = callback
elif channel == self.EVENT_NAME_RESULTS:
self.socketIO.on(channel, partial(self.unpack_results, callback))
else:
self.socketIO.on(channel, callback)
def start_stream(self, stream_type, **stream_parameters):
"""Starts new stream for given type with given parameters"""
if stream_type:
self.subscribe(stream_type, **stream_parameters)
else:
self.handle_error("You need to set a stream type")
def subscribe(self, stream_type, **parameters):
"""Subscribe to stream with give parameters."""
parameters["stream_type"] = stream_type
if (stream_type == "result") and ("buffering" not in parameters):
parameters["buffering"] = True
self.socketIO.emit(self.EVENT_NAME_SUBSCRIBE, parameters)
#.........这里部分代码省略.........
示例15: generate_id
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import disconnect [as 别名]
_id_symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
def generate_id(length, symbols=_id_symbols):
n = len(symbols)
symbol_gen = (symbols[random.randrange(0, n)] for i in range(length))
return ''.join(symbol_gen)
if len(sys.argv) == 1:
print "Usage: agent.py <room_id>"
sys.exit(1)
else:
room_id = sys.argv[1]
user_name = 'INDRA'
user_id = generate_id(USER_ID_LEN)
socket = SocketIO('localhost', 3000)
sa_payload = {'userName': user_name,
'room': room_id,
'userId': user_id}
socket.on('message', on_message)
socket.on('userList', on_user_list)
socket.emit('subscribeAgent', sa_payload, ack_subscribe_agent)
try:
socket.wait()
except KeyboardInterrupt:
pass
print "Disconnecting..."
socket.emit('disconnect')
socket.disconnect()