当前位置: 首页>>代码示例>>Python>>正文


Python SocketIO.define方法代码示例

本文整理汇总了Python中socketIO_client.SocketIO.define方法的典型用法代码示例。如果您正苦于以下问题:Python SocketIO.define方法的具体用法?Python SocketIO.define怎么用?Python SocketIO.define使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在socketIO_client.SocketIO的用法示例。


在下文中一共展示了SocketIO.define方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
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,代码行数:27,代码来源:bot.py

示例2: KHUBConnection

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
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,代码行数:37,代码来源:KHUBConnection.py

示例3: YetiSocket

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [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()
开发者ID:cnewham,项目名称:yeti-cam,代码行数:34,代码来源:cam-socket.py

示例4: __init__

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
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,代码行数:31,代码来源:glws_conn.py

示例5: DocumentSyncTest

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [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))
开发者ID:veasy,项目名称:colmark,代码行数:34,代码来源:document_sync_test.py

示例6: socketIOClient

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
class socketIOClient(object):
    def __init__(self):
        self._server_ip = 'localhost'
        self._server_port = 5000
        self.socketio = None

    def onConnect(self):
        logger.info("From Server: onConnect")

    def onDisconnect(self):
        logger.info("From Server: onDisconnect")

    def onReconnect(self):
        logger.info("From Server: onReconnect")

    def connect(self):
        logger.info("Connecting ...")
        try:
            self.socketio = SocketIO(self._server_ip, self._server_port, Main)
            self.socketio_namespace = self.socketio.define(TestClient, Namespace)
        except Exception, e:
            logger.error("connect() except {0}".format(e))
            return

        try:
            self.socketio_namespace.on('connect', self.onConnect)
            self.socketio_namespace.on('disconnect', self.onDisconnect)
            self.socketio_namespace.on('reconnect', self.onReconnect)
            logger.info("socketio.on() success")
        except Exception, e:
            logger.error("socketio.on() except {0}".format(e))
开发者ID:mattli001,项目名称:socketio_client_test,代码行数:33,代码来源:socketio.py

示例7: Transaction

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
class Transaction(object):
    def __init__(self):
        self.custom_timers = {}
        self.word_list = buildArray( )
        self.word_list_length = len(self.word_list)
        self.socketIO = SocketIO(HOST, PORT)
        self.socketIO.define(Namespace)
                    
    def makeCall( self, jsonObject ):
        
        start_timer = time.time()

        self.socketIO.message(jsonObject)
        self.socketIO.wait(0.01)
        namespace = self.socketIO.get_namespace()
        #print namespace.response
    
        latency = time.time() - start_timer
    
        self.custom_timers['trie_service_sockets'] = latency
    
        #if latency > 5:
            #writeErrorInfo('latency value of %f with %s' %(latency, url) )
        #if r.status_code != 200:
            #writeErrorInfo('status code with %s is %s' %(r.status_code, url) )
    
        #assert (r.status_code == 200), 'Bad HTTP Response'
        #assert ('suggestions' in namespace.response), 'No suggestions'
    
    def run(self):
        
        #get a random word from the word_list and call to typeahead
        whichPhrase = random.randrange(0,self.word_list_length)
        phrase = self.word_list[whichPhrase]
        word = phrase.split(" ")[0]
        #print 'word is %s' % word
        message = ""
        jsonObject = ""
        #loop through the chars in the word skipping the first
        #for char in word:
        #    message = message + char
        #    jsonObject = {'@class': 'com.glg.service.TrieObject', 'entity':'cm', 'prefix':message}
        #    self.makeCall( jsonObject )
        
        jsonObject = {'@class': 'com.glg.service.TrieObject', 'entity':'cm', 'prefix':word}
        self.makeCall( jsonObject )
开发者ID:dgriffis,项目名称:multi-mechanize,代码行数:48,代码来源:v_userSocketTest.py

示例8: play

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
def play(handler):
    token = raw_input('Enter your token: ')
    global play_reversi
    play_reversi = handler
    # Use socketio with defined Namespace
    socketIO = SocketIO('localhost', 8100, params={'token': token})
    gameplay = socketIO.define(ReversiNamespace, '/play')

    socketIO.wait()
开发者ID:PhyTeam,项目名称:ReversiGame,代码行数:11,代码来源:reversi_client.py

示例9: userver_listening

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
def userver_listening():
    try:
        socketio_cli = SocketIO(host=HOST, port=PORT, params={'app_eui': APP_EUI, 'token': TOKEN})
        # global socketio_cli
        test_namespace = socketio_cli.define(TestNamespace, '/test')
        socketio_cli.wait()

    except Exception as e:
        ws_listening()
开发者ID:qitianchan,项目名称:LightLights,代码行数:11,代码来源:receive.py

示例10: punisher

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
def punisher(configs):

    socket = SocketIO(configs['server_addr'], configs['server_port'])
    punisher_ns = socket.define(PunisherNamespace, '/punisher')

    try:
        socket.wait()

    except KeyboardInterrupt:

        pass
开发者ID:s0lst1c3,项目名称:sentrygun,代码行数:13,代码来源:sentrygun.py

示例11: openStream

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
    def openStream(self, id, options, callback):
        try:
            if options['query']:
                d = options
        except:
            ##options is an string
            d = {'query':options}


        if (self.accessToken):
            url= self.base+':'+str(self.port)+'/api/wo/'+ id + '/endpoint'
            headers={ 'Authorization': 'Bearer ' + self.accessToken}
            
            r= requests.get(url,params=d, headers=headers, verify=False)
            
        if ('r' in locals() and r.status_code == 200):
                sid = r.content
#                print "sid:---"+sid
#                sio = 'http://webobservatory.soton.ac.uk'#+sid
                #sio = 'dev-001.ecs.soton.ac.uk'
                #print sio
#                class Namespace(BaseNamespace):
#                    def on_connect(self):
#                        print '[Connected]'

                class dataNamespace(BaseNamespace):
                    #def on_aaa_response(self, *args):
                    #    print('on_aaa_response', args)
                    def on_connect(self):
                        print '[Connected]'
                        pass

                def process(data):
#                    print "process data"
#                    print data
                    callback(False, data,socketIO)


#               socketIO = SocketIO(sio,443,LoggingNamespace,verify=False)
                socketIO = SocketIO(self.base,self.port, verify=False)
#                socketIO = SocketIO(self.base, 9090)
                data_namespace = socketIO.define(dataNamespace,'/'+sid)


                #data_namespace.emit('stop')
                data_namespace.on('chunk',process)
#                data_namespace.emit('stop')
#                socketIO.emit("stop")
#                socketIO.wait(seconds=1)
#                data_namespace.wait()
                socketIO.wait()
        else:
            callback("[ERROR] Open Stream Failed: Stream opening failed for:"+id,None,None)
开发者ID:jiadiyao,项目名称:wo-api-python,代码行数:55,代码来源:wo.py

示例12: startcsdfeed

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
def startcsdfeed(bot, trigger):
    """CSD feed"""
    class MainNamespace(BaseNamespace):
        def on_change(self, change):
            if change['type'] == 'categorize':
                if change['title'] == 'Category:Candidates for speedy deletion':
                    if re.search('.\]\] added to category$', change['comment']):
                        strippedtitle = change['comment'].lstrip('[[').rstrip(']] added to category')
                        unspacedstrippedtitle = strippedtitle.replace(' ','_')
                        bot.say('[Page CSD] ' + 'Wiki: ' + change['wiki'] + ' | Page: http://enwp.org/' + unspacedstrippedtitle + ' | User: ' + change['user'])

        def on_connect(self):
            bot.say('Connected.')
            self.emit('subscribe', 'en.wikipedia.org')
            bot.say('Subscribed to en.wikipedia.org feed.')

    bot.say('Connecting...')
    socketIO = SocketIO('https://stream.wikimedia.org')
    socketIO.define(MainNamespace, '/rc')

    socketIO.wait()
开发者ID:piagetbot,项目名称:sopel,代码行数:23,代码来源:csdfeed.py

示例13: connect

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
	def connect(self, cb):

		appId = self._xpush.appId
		userId = self._xpush.userId
		deviceId = self._xpush.deviceId
		token = self._xpush.token
		serverName = self._server.get( "name" )

		q = {
			"A" : appId,
			"U" : userId, 
			"D" : deviceId,
			"C" : self.chNm,
			"S" : serverName
		}

		if self._type == TYPE_SESSION :
			q["TK"] = token  

		if self._channelOnly == True :
			q["MD"] = "CHANNEL_ONLY";

		strArr = self._server.get( "url" ).split(":")
		protocol = strArr[0]
		host =  strArr[1].replace( "//", "" )
		port = int( strArr[2] )

		socketIO = SocketIO( host, port, params= q )

		if self._type == TYPE_SESSION :
			self.sessionNamespace = socketIO.define(SessionNamespace, "/"+self._type)
		else :
			self.channelNamespace = socketIO.define(ChannelNamespace, "/"+self._type)
		#socketIO.emit("aaa", {"xxx": "yyy"})

		self._connected = True
		self._socket = socketIO
		#self._socket.wait()

		cb()
开发者ID:xpush,项目名称:lib-xpush-python,代码行数:42,代码来源:connection.py

示例14: Socket

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
class Socket(object):
	def __init__(self, url, port, headers):
		self.socketIO = SocketIO(url, port, headers=headers)
		self.reader_namespace = self.socketIO.define(ReaderNamespace, '/readers')

	def statusUpdate(self, message):
		print message
		self.socketIO.wait(seconds=0.1)
		self.reader_namespace.emit('status update', message)

	def tagReading(self, package):
		self.reader_namespace.emit('tag reading', json.dumps(package))
		self.socketIO.wait(seconds=0.1)
开发者ID:connorgiles,项目名称:CG-Work,代码行数:15,代码来源:connection.py

示例15: Server

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import define [as 别名]
class Server(object):
    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.proxies = {}

    def set_proxy(self, protocol, url):
        self.proxies[protocol] = url
        logger.info('set proxy %s=%s' % (protocol, url))
    
    def start(self):
        logger.info('Server started [%s:%d]...' % (self.host, self.port))
        self.socket = SocketIO(self.host, self.port, proxies=self.proxies)
        self.namespace = self.socket.define(HubNamespace)
        self.namespace.set_home('sungtaek')
        self.namespace.add_agent(Led('led'))
        self.socket.wait()
开发者ID:sungtaek,项目名称:smarthome-hub,代码行数:19,代码来源:server.py


注:本文中的socketIO_client.SocketIO.define方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。