本文整理汇总了Python中socketIO_client.SocketIO类的典型用法代码示例。如果您正苦于以下问题:Python SocketIO类的具体用法?Python SocketIO怎么用?Python SocketIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SocketIO类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: run
def run(self, args):
print('Listening to %s' % args.relay_url)
try:
worker = Worker(args.server_url, args.queue_token)
worker.work()
Namespace.channel = 'q/' + args.queue_token
Namespace.worker = worker
socket = SocketIO(
args.relay_url, Namespace=Namespace, wait_for_connection=False)
socket.wait()
except ServerConnectionError:
print_error('The server is down. Try again later.')
except RelayConnectionError:
print_error('The relay is down. Try again later.')
except HTTPBadRequest:
print_error(
'There was an error processing your request.\n'
'- Check that the server URL is correct (--server_url).\n'
'- Upgrade the framework (pip install -U crosscompute).')
except HTTPUnauthorized:
print_error(
'The server rejected the token. '
'Make sure your token is valid.')
except KeyboardInterrupt:
pass
开发者ID:crosscompute,项目名称:crosscompute,代码行数:25,代码来源:work.py
示例2: Broadcaster
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()
开发者ID:davidjonas,项目名称:Mediawerf,代码行数:25,代码来源:broadcaster.py
示例3: __init__
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()
开发者ID:Flerb,项目名称:Wii-Scale,代码行数:30,代码来源:wii-scale.py
示例4: Command
class Command(BaseCommand):
args = '<hostname> <public port> <runserver port> <socket port>'
help = 'Listens over socket.io websocket'
def handle(self, *args, **options):
if len(args) != 4:
raise Exception("Arguments needed: %s" % self.args)
# parse arguments
runserver_host = "%s:%s" % (args[0], args[2])
runserver_cmd = "python manage.py runserver %s" % runserver_host
nodejs_cmd = "node %s %s %s %s" % (nodjango_indexjs, args[1], args[2], args[3])
try:
# start nodejs proxy
proc2 = Popen(nodejs_cmd, shell=True, preexec_fn=os.setsid, stdout=sys.stdout, stderr=sys.stderr)
# start django runserver
proc1 = Popen(runserver_cmd, shell=True, preexec_fn=os.setsid, stdout=sys.stdout, stderr=sys.stderr)
time.sleep(2)
# start django private socketio
self.socket = SocketIO('127.0.0.1', int(args[3]), Namespace=DjangoNamespace)
print '* * *\t django socket started'
self.socket.wait()
finally:
print 'killing...'
os.killpg(proc1.pid, signal.SIGTERM)
os.killpg(proc2.pid, signal.SIGTERM)
print 'killed!'
开发者ID:ginking,项目名称:django-socketio-events,代码行数:32,代码来源:runserverjs.py
示例5: login
def login():
image_response = fetch('https://livechan.net/captcha.jpg')
image_data = image_response.read()
with open('captcha.jpg', 'w') as f:
f.write(image_data)
os.system("open captcha.jpg")
digits = int(raw_input("enter the captcha: "))
post_params = {}
post_params["digits"] = digits
login_response = post('https://livechan.net/login', post_params)
login_html = login_response.read()
print login_html
livechan_pass = get_password()
if livechan_pass == "":
login()
global socketIO
socketIO = SocketIO('https://livechan.net',
cookies={'password_livechan': livechan_pass})
socketIO.on('chat', on_chat)
socketIO.on('user_count', on_user_count)
thread.start_new_thread ( socketIO.wait, () )
开发者ID:emgram769,项目名称:livechan-tui,代码行数:25,代码来源:livechan-client.py
示例6: SocketIOHandler
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!')
开发者ID:lwz7512,项目名称:logmotor,代码行数:31,代码来源:SocketIOHandler.py
示例7: main
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)
开发者ID:pilgrimbeart,项目名称:nodejs-blackboard,代码行数:27,代码来源:socktest.py
示例8: main
def main():
conf_file = sys.argv[1] if len(sys.argv) > 1 else "config.yml"
with open(conf_file) as f:
config = yaml.load(f)
channel = config["irc"]["channel"]
sio = SocketIO(config["state"]["host"], config["state"]["port"])
public_ns = sio.define(PublicNamespace, '/public')
private_ns = sio.define(PrivateNamespace, '/private')
bot = AvalonBot(private_ns)
# TODO: figure out a less hacky solution.
public_ns.bot = bot
public_ns.channel = channel
private_ns.bot = bot
sio_t = threading.Thread(target=sio.wait)
sio_t.start()
bot.connect(config["irc"]["server"], config["irc"]["port"])
bot.register(config["irc"]["nick"])
bot.join(channel)
bot.listen()
开发者ID:pefoley2,项目名称:avalon,代码行数:25,代码来源:bot.py
示例9: login
def login(callback=on_chat):
#image_response = fetch('https://livechan.net/captcha.jpg')
#image_data = image_response.read()
#with open('captcha.jpg', 'w') as f:
# f.write(image_data)
#os.system("open captcha.jpg")
#digits = int(raw_input("enter the captcha: "))
#post_params = {}
#post_params["digits"] = digits
#login_response = post('https://livechan.net/login', post_params)
#login_html = login_response.read()
cookie = cookielib.Cookie(version=0, name='password_livechan', value='somepassword', port=None, port_specified=False, domain='livechan.net',
domain_specified=False, domain_initial_dot=False,
path='/', path_specified=True, secure=False, expires=None,
discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
cookies.set_cookie(cookie)
livechan_pass = get_password()
if livechan_pass == "":
print "wrong password"
login()
global socketIO
socketIO = SocketIO('https://livechan.net',
cookies={'password_livechan': livechan_pass})
socketIO.on('chat', callback)
socketIO.on('request_location', on_request_location)
thread.start_new_thread ( socketIO.wait, () )
开发者ID:emgram769,项目名称:livechan-ircd,代码行数:31,代码来源:livechanapi.py
示例10: __init__
class makeSocket:
def __init__(self):
self.socket = SocketIO("https://glws.org/fuck")
self.fn = self.socket.define(fuck, "/fuck")
def emitready(self):
try:
self.fn.emit("isReady",{"wanna_fuck": "no thanks I\'m under age"})
self.socket.wait(seconds=3)
global globalready
temp = globalready
globalready = None
return temp
except TypeError:
print 'something went wrong doing a ready command please try again'
return False
def emitgetdata(self, data):
try:
self.fn.emit("sendData", data)
self.socket.wait(seconds=0.8)
global globalgetData
temp = globalgetData
globalgetData = None
return temp
except TypeError:
print 'something went wrong doing a sendData command please try again'
return False
开发者ID:craked5,项目名称:opskins_bot,代码行数:29,代码来源:glws_conn.py
示例11: test_emit_with_callback
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)
开发者ID:graingert,项目名称:socketIO-client,代码行数:7,代码来源:tests.py
示例12: run_socketio
def run_socketio(args):
log.debug("launched as socket.io client")
def printout(text):
if not text is None:
print chr(27) + "[2J" # clear screen
t = text.decorated(style=STYLES[args.style]())
print "--------8<----------------8<----------------8<---------------8<--------"
print t
print "-------->8---------------->8---------------->8--------------->8--------"
res = requests.get("http://%s:%s/%s%s" % (args.host, args.port, args.path, args.pad))
cookie = res.headers['set-cookie']
cookie = dict([(cookie[:cookie.find("=")], cookie[cookie.find("=")+1:])])
reconnect = True
while reconnect:
socketIO = SocketIO(args.host, args.port, EtherpadService,
transports=['xhr-polling',
'websocket'],
cookies=cookie,
padid=args.pad,
cb=printout)
reconnect = socketIO.wait()
del socketIO
开发者ID:guyzmo,项目名称:PyEtherpadLite,代码行数:26,代码来源:client.py
示例13: main
def main():
app = App(False)
socketIO = SocketIO(API_URL, 443, LoggingNamespace)
socketIO.on('location', app.on_ws_location)
Thread(target=socketIO.wait).start()
app.MainLoop()
开发者ID:Proj-P,项目名称:project-p-systray,代码行数:7,代码来源:main.py
示例14: KHUBConnection
class KHUBConnection(object):
""" Class to connect to the Kyanite backend server to send/receive data.
Attributes:
name: Name of the sensor/client
server:Name or IP address of server .
port:Port address of server .
namespace: namespace at server .
"""
def __init__(self, name, server, port, namespace):
self.socketIO = SocketIO(server, port)
self.msg_namespace = self.socketIO.define(BaseNamespace, namespace)
# self.msg_namespace.emit('sname', name)
def send(self, eventType, data):
"""
Send the data as JSON data to the server.
Attributes:
eventType: Data event to be triggered at the server (String)
data: Data to be sent (JSON) .
"""
self.msg_namespace.emit(eventType, data)
def onEvent(self, eventName, callBack):
"""
Trigger callback for a given event.
Attributes:
eventName: Event name triggered by the server (String)
callBack: Call back function name .
"""
self.msg_namespace.on('ops', callBack)
def wait(self, options):
"""Wait the thread before exiting."""
self.socketIO.wait(seconds=options)
开发者ID:rboldu,项目名称:AirTurtle,代码行数:35,代码来源:KHUBConnection.py
示例15: send
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)
开发者ID:jmccormack200,项目名称:ARCAM-Net-Public,代码行数:27,代码来源:alfredCallBack.py
示例16: YetiSocket
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()
开发者ID:cnewham,项目名称:yeti-cam,代码行数:32,代码来源:cam-socket.py
示例17: main
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)
开发者ID:adommeti,项目名称:rockstor-core,代码行数:59,代码来源:cpu_info.py
示例18: play
def play(handler):
token = raw_input('Enter your token: ')
global play_reversi
play_reversi = handler
# Use socketio with defined Namespace
socketIO = SocketIO('localhost', 8100, ReversiNamespace, params={'token': token})
socketIO.wait()
开发者ID:ngovietbao,项目名称:ReversiGame,代码行数:8,代码来源:reversi_client.py
示例19: test_events
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)
开发者ID:graingert,项目名称:socketIO-client,代码行数:8,代码来源:tests.py
示例20: run
def run(self):
""" Method that runs forever """
while True:
socketIO = SocketIO(
'rover-sensors-data-provider.52.35.15.130.nip.io',
proxies={'https': 'http://proxy.compaq.com:8080'})
socketIO.on('telemetry', self.set_telemetry_data)
socketIO.wait()
开发者ID:LumbaJack,项目名称:Oscon-Demo,代码行数:8,代码来源:getoperations.py
注:本文中的socketIO_client.SocketIO类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论