本文整理汇总了Python中socketIO_client.SocketIO.emit方法的典型用法代码示例。如果您正苦于以下问题:Python SocketIO.emit方法的具体用法?Python SocketIO.emit怎么用?Python SocketIO.emit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socketIO_client.SocketIO
的用法示例。
在下文中一共展示了SocketIO.emit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_emit_with_callback
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def test_emit_with_callback(self):
global ON_RESPONSE_CALLED
ON_RESPONSE_CALLED = False
socketIO = SocketIO('localhost', 8000)
socketIO.emit('aaa', PAYLOAD, on_response)
socketIO.wait(forCallbacks=True)
self.assertEqual(ON_RESPONSE_CALLED, True)
示例2: Client
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
class Client(object):
def __init__(self, client_factory):
self.logger = logging.getLogger('Graduation')
self.socket = None
self.client_factory = client_factory
self.host = client_factory.host
self.port = client_factory.port
def connect(self):
self.socket = SocketIO(self.host, self.port, LoggingNamespace);
self.socket.on('device_data_response', self.on_response);
self.sendMessage(0)
self.socket.wait()
def on_response(self):
time.sleep(2);
tem = random.randint(0, 40);
self.sendMessage(tem)
def sendMessage(self, tem):
data = dict();
data["id"] = 1
data["name"] = "name"
params = dict();
params["temperature"] = tem
data["params"] = params
self.socket.emit('device_data', data)
示例3: send
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def send (lines):
print(lines)
data = []
for line in lines:
if line == "\n":
pass
else:
print (line)
frame = line.strip()[2:-3].split(', ')
freqandtime = frame[1].split('\\')[0]
freq,time = freqandtime[1:].split('%')
mac = frame[0]
if not data:
data = [mac,freq,time]
elif float(data[2]) <= float(time):
print("HERE")
data = [mac,freq,time]
print ("Outputting: " + str(data[1]))
sleep(4)
socketIO = SocketIO('127.0.0.1', 5000)
socketIO.emit('alfred set freq', str(data[1]))
socketIO.wait(1)
示例4: connect
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def connect():
"""Sends the starting signal to the server."""
arduino = serial.Serial('/dev/serial/by-id/usb-Gravitech_ARDUINO_NANO_13BP1066-if00-port0', 115200)
info_start = {'purpose': 'realtime-sender', 'groupID': "cwa2", 'userID': "r0462183"}
metadata = {'other':"trip ended"} #string "trip ended" stored in metadata under key 'other' to be able to filter on realtime trips easier on the bicyclus website
print "Setting up for server connection ..."
while True: #connection tests everywhere they are needed to minimise amount of connection errors
if try_connection() == True:
socketIO = SocketIO('dali.cs.kuleuven.be', 8080)
break
time.sleep(2)
while True:
if try_connection() == True:
socketIO.on('server_message', on_emit)
break
socketIO.wait(2)
print "Trying to send start signal for trip ..."
while True:
if try_connection() == True:
socketIO.emit('start', json.dumps(info_start), on_emit)
print "Connection verified, start signal sent."
socketIO.wait(2)
break
socketIO.wait(2)
info_end = {"_id":startID, "meta": metadata}
return info_end
示例5: ListenIO
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def ListenIO(self):
# socketIO = SocketIO('192.168.1.33', 3000)
# socketIO = SocketIO('192.168.1.223', 3000)
socketIO = SocketIO('localhost', 3000)
socketIO.on('serverToPython', self.listener)
socketIO.emit('clientType', 'Python')
socketIO.wait(seconds = 6000)
示例6: Broadcaster
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
class Broadcaster(object):
port = 8080
host = "localhost"
def __init__(self, port=8080, host="localhost"):
self.port = port
self.host = host
self.socketIO = SocketIO(host, int(port))
self.socketIO.on("ack", self.logACK)
def logACK(self, data):
print("Acknowledgement received for %s" % data['original'])
def emit(self, event, data):
self.socketIO.emit(event, data)
def on(self, event, callback):
self.socketIO.on(event, callback)
def wait(self, millis):
self.socketIO.wait(millis)
def wait_forever(self):
self.socketIO.wait()
示例7: __init__
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
class WebSocketIO:
def __init__(self):
global host
global port
self.socketIO = SocketIO(host, port, LoggingNamespace)
self.socketIO.on('wiiscale-connect', self.receive_connect)
self.socketIO.on('wiiscale-disconnect', self.receive_disconnect)
def wait(self):
self.socketIO.wait(seconds = 1)
def send_status(self, status):
self.socketIO.emit('wiiscale-status', {'status': status})
def send_weight(self, totalWeight):
self.socketIO.emit('wiiscale-weight', {'totalWeight': totalWeight})
# def send_connection_status(self, status):
# self.socketIO.emit('wiiscale-connection', {'status': status})
# Accepts True or False as argument
def receive_connect(self):
global sleep
sleep = False
def receive_disconnect(self):
global board
global sleep
sleep = True
board.disconnect()
示例8: WebsocketRemoteControl
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
class WebsocketRemoteControl(object):
def __init__(self, bot):
self.bot = bot
self.host, port_str = self.bot.config.websocket_server_url.split(":")
self.port = int(port_str)
self.sio = SocketIO(self.host, self.port)
self.sio.on("bot:process_request:{}".format(self.bot.config.username), self.on_remote_command)
self.thread = threading.Thread(target=self.process_messages)
def start(self):
self.thread.start()
return self
def process_messages(self):
self.sio.wait()
def on_remote_command(self, command):
name = command["name"]
command_handler = getattr(self, name, None)
if not command_handler or not callable(command_handler):
self.sio.emit(
"bot:send_reply", {"response": "", "command": "command_not_found", "account": self.bot.config.username}
)
return
if "args" in command:
command_handler(*args)
return
command_handler()
def get_player_info(self):
player_info = self.bot.get_inventory()["responses"]["GET_INVENTORY"]
self.sio.emit(
"bot:send_reply", {"result": player_info, "command": "get_player_info", "account": self.bot.config.username}
)
示例9: waiter
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def waiter(username, password, usertype, session_key):
ioplugin = SocketIO(self.host, self.port)
def on_identify(message):
if not 'ID' in message:
obj = {
'username': username,
'password': password,
'usertype': usertype,
'django_id': session_key
}
ioplugin.emit('login', obj)
else:
self.do_event(ioplugin)
# end if
# end def
def on_error_login():
raise "Error"
# end def
def on_success_login():
self.do_event(ioplugin)
# end def
ioplugin.on('identify', on_identify)
ioplugin.on('error-login', on_error_login)
ioplugin.on('success-login', on_success_login)
ioplugin.emit('identify', {'django_id': session_key, 'usertype': usertype})
ioplugin.wait(seconds=1)
示例10: main
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def main():
global g_socketIO,g_start_time,g_objects_lock
g_objects_lock = threading.Lock()
if(len(sys.argv)<2):
print "Usage:",sys.argv[0]," {S|L|SL} (S=speaking, L=listening) - defaults to SL"
if(len(sys.argv)==1):
sys.argv.append("SL") # Default arguments
print "Listening to "+HOST+":"+str(PORT)
g_socketIO = SocketIO(HOST, PORT, Namespace)
print "Emitting adduser"
g_socketIO.emit("adduser",socket.getfqdn()+";"+str(os.getpid()))
g_start_time = time.time()
if("S" in sys.argv[1]):
print "Starting speaking"
thread1 = threading.Thread(target=heartbeat_thread)
thread1.daemon = True
thread1.start()
if("L" in sys.argv[1]):
print "Starting listening"
g_socketIO.wait()
else:
time.sleep(60*60*24*365*100)
示例11: send_data
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def send_data(save_path):
"""
Sends all the data files that are present in the specified path to the Qbike server.
:param save_path: Requires the path in which the trips are saved.
:return: Nothing. The data is sent to the Server and the txt files are removed from the path's directory.
"""
end = False
Trip_nb = 100
while end == False:
if not os.path.isfile('C:\Users\Joren\Documents\Ir 1B\P&O\P&O 3\Tryouts\Trips\Trip1.txt'):
end = True
else:
for nb in reversed(range(0, 100)):
Trip = os.path.join(save_path, "Trip" + str(nb) + ".txt")
Trip_nb = str(nb)
if os.path.isfile(Trip):
break
Trip_path = os.path.join(save_path, r"Trip" + Trip_nb + r".txt")
with open(Trip_path, "r") as Trip:
batch = json.load(Trip)
info = {'purpose': 'batch-sender', 'groupID': "cwa2", 'userID': ID}
socketIO = SocketIO('dali.cs.kuleuven.be', 8080)
socketIO.on('server_message', on_response)
socketIO.emit('start', json.dumps(info), on_response)
socketIO.wait(2)
socketIO.emit('batch-tripdata', json.dumps(batch), on_response)
socketIO.wait(5)
os.remove(Trip_path)
print "Sent Data"
示例12: main
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def main():
logging.basicConfig(filename=settings.WEBSOCKET_CLIENT['logfile'],
level=logging.DEBUG)
logging.debug('Started logging')
num_samples = 120;
socketIO = SocketIO('localhost', settings.NGINX_WEBSOCKET_PORT, secure=True)
max_ts = None
prev_cpu_data = [];
# TODO handle multiple cpus
for i in range(num_samples):
prev_cpu_data.append({u'umode': 0, u'umode_nice': 0, u'smode': 0, u'idle': 0, u'ts': None})
while True:
# read from db
auth_params = {'apikey': 'adminapikey'}
# Get cpu metrics
r = requests.get('https://localhost/api/sm/cpumetric/?format=json', verify=False, params = auth_params)
cpu_data = r.json()
tmp = []
# find max timestamp
if (len(cpu_data) < num_samples):
for i in range(num_samples - len(cpu_data)):
tmp.append({u'umode': 0, u'umode_nice': 0, u'smode': 0, u'idle': 0, u'ts': None})
tmp.extend(cpu_data)
cpu_data = tmp
cpu_util = [];
for i in range(num_samples):
cpu_util.append({
'umode': cpu_data[i][u'umode'] - prev_cpu_data[i][u'umode'],
'umode_nice': cpu_data[i][u'umode_nice'] - prev_cpu_data[i][u'umode_nice'],
'smode': cpu_data[i][u'smode'] - prev_cpu_data[i][u'smode'],
'idle': cpu_data[i][u'idle'] - prev_cpu_data[i][u'idle']
})
# send to websocket
new_cpu_data = False
if cpu_data[num_samples-1][u'ts'] != prev_cpu_data[num_samples-1][u'ts']:
new_cpu_data = True
prev_cpu_data = cpu_data
msg = {}
if new_cpu_data:
msg['cpu_util'] = cpu_util
# Get loadavg metrics
r = requests.get('https://localhost/api/sm/loadavg/?format=json', verify=False, params = auth_params)
load_data = r.json()
msg['load_avg'] = load_data
if (r.status_code != 200):
socketIO.emit('sm_data_update', {'msg': json.dumps(msg)}, on_response)
else:
logging.debug('invalid CPU data - JSON data invalid')
# Sleep before getting the next set of data
time.sleep(5)
示例13: check_pushould
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def check_pushould(self):
socketio = SocketIO(self.pushurl,
params={"transports": ["polling", "websocket"],
"client_token": str(self.client_token)},
verify=False)
socketio.on('send', self.add_message)
socketio.emit("subscribe", {"room": "sadpandapush"})
socketio.wait()
示例14: test_events
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def test_events(self):
global ON_RESPONSE_CALLED
ON_RESPONSE_CALLED = False
socketIO = SocketIO('localhost', 8000)
socketIO.on('ddd', on_response)
socketIO.emit('aaa', PAYLOAD)
sleep(0.5)
self.assertEqual(ON_RESPONSE_CALLED, True)
示例15: test_events
# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import emit [as 别名]
def test_events(self):
global ON_RESPONSE_CALLED
ON_RESPONSE_CALLED = False
socketIO = SocketIO('localhost', 8000, transports=['xhr-polling'])
socketIO.on('ddd', on_response)
socketIO.emit('aaa', PAYLOAD)
sleep(2)
self.assertEqual(ON_RESPONSE_CALLED, True)