本文整理汇总了Python中socketIO_client.SocketIO类的典型用法代码示例。如果您正苦于以下问题:Python SocketIO类的具体用法?Python SocketIO怎么用?Python SocketIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SocketIO类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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()
示例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()
示例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!'
示例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, () )
示例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!')
示例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)
示例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()
示例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, () )
示例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
示例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)
示例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
示例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()
示例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)
示例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)