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


Python SocketIO.connect方法代码示例

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


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

示例1: SocketIOHandler

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import connect [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!')
开发者ID:lwz7512,项目名称:logmotor,代码行数:33,代码来源:SocketIOHandler.py

示例2: test_channels

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import connect [as 别名]
 def test_channels(self):
     mainSocket = SocketIO('localhost', 8000, Namespace)
     chatSocket = mainSocket.connect('/chat', Namespace)
     newsSocket = mainSocket.connect('/news', Namespace)
     newsSocket.emit('aaa', PAYLOAD)
     sleep(0.5)
     self.assertNotEqual(mainSocket.namespace.payload, PAYLOAD)
     self.assertNotEqual(chatSocket.namespace.payload, PAYLOAD)
     self.assertEqual(newsSocket.namespace.payload, PAYLOAD)
开发者ID:graingert,项目名称:socketIO-client,代码行数:11,代码来源:tests.py

示例3: socketThread

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import connect [as 别名]
def socketThread():
    """
    Reads the socketQueue and fill the geo location info(lat, long, city, country) then send new updated
    data to server. After sending to server put the updated feed object to databaseQueue
    """
    global socketQueue, databaseQueue, IS_RUNNING, socketIOHost, socketIOPort

    def __toJSON(newFeed):
        return '{ "url":"%s", "saddr":"%s", "sport":"%s", "sha512":"%s", "md5":"%s", ' \
               '"country":"%s", "city":"%s", "x": "%f", "y": "%f"}' \
                     % (newFeed.url, newFeed.saddr, newFeed.sport, newFeed.sha512, newFeed.md5,
                        newFeed.country, newFeed.city, newFeed.longitude, newFeed.latitude)

    def _sendNewFeed(chatSocket, newFeed):
        info = freegeoip.getCityInfoByIp(newFeed.saddr)
        if info:
            newFeed.longitude = info['longitude']
            newFeed.latitude = info['latitude']
            newFeed.country = info['country_code3']

            city = info['city']
            if city:
                try:
                    city = city.decode('utf-8', 'ignore')
                except:
                    city = ''

                newFeed.city = city

            # TODO: Add other options except for daddr
            #coordinate = "{ \"country\":\"%s\", \"city\":\"%s\", \"x\": \"%f\", \"y\": \"%f\"}" % (newFeed.country, newFeed.city, info['longitude'], info['latitude'])
            coordinate = __toJSON(newFeed)
            chatSocket.emit('update', coordinate)
            databaseQueue.put(newFeed)

    try:
        socketIO = SocketIO(socketIOHost, socketIOPort)
        chatSocket = socketIO.connect('/new-event')
        print 'socketThread started, IS_RUNNING:', IS_RUNNING
        while IS_RUNNING:
            try:
                newFeed = socketQueue.get(True, 1)
                _sendNewFeed(chatSocket, newFeed)
                socketQueue.task_done()
            except Empty:
                pass
    except:
        traceback.print_exc()
        stopExecution()
        #IS_RUNNING = False

    print 'socketThread finished...'
开发者ID:CyberIntelMafia,项目名称:malwarez,代码行数:54,代码来源:feedReader.py

示例4: Namespace

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import connect [as 别名]
from socketIO_client import SocketIO, BaseNamespace

class Namespace(BaseNamespace):

    def on_connect(self, socketIO):
        print '[Connected]'
        self.socketIO.emit('subscribe' , {'my': 'mynick'});

    def on_disconnect(self):
        print '[Disconnected]'

    def on_error(self, name, message):
        print '[Error] %s: %s' % (name, message)

    def on_message(self, id, message):
        print '[Message] %s: %s' % (id, message)

    def on_welcome(self, id, message):
        print '[Welcome] %s: %s' % (id, message)

    def on_subscribe(self, id, message):
        print '[Welcome] %s: %s' % (id, message)
    
    def on_test(self, message):
        print '[Test] message: %s' % (message)

socketIO = SocketIO('127.0.0.1', 8000)
chatSocket = socketIO.connect('/chat', Namespace)
#socketIO.emit('aaa', {'bbb': 'ccc'})
socketIO.wait()
开发者ID:CyberIntelMafia,项目名称:malwarez,代码行数:32,代码来源:socketio-client.py

示例5: WaptTestHost

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import connect [as 别名]
class WaptTestHost(object):
    def __init__(self,config_filename = 'c:/wapt/wapt-get.ini'):
        self.config_filename = config_filename
        self.config = WaptServiceConfig(config_filename)
        self.socketio_client = None
        self.wapt_remote_calls = None

    def run(self):
        self.config.reload_if_updated()
        with Wapt(config_filename = self.config.config_filename) as tmp_wapt:
            logger.info('Starting socketio on "%s://%s:%s" ...' % (self.config.websockets_proto,self.config.websockets_host,self.config.websockets_port))
            logger.debug('Certificate checking : %s' %  self.config.websockets_verify_cert)
            while True:
                try:
                    if not self.socketio_client and self.config.websockets_host:
                        logger.debug('Creating socketio client')
                        logger.debug('Proxies : %s'%self.config.waptserver.proxies)
                        # bug in socketio... ? we must not pass proxies at all (even None) if we don"t want to switch to polling mode...
                        kwargs = {}
                        if self.config.waptserver.proxies and self.config.waptserver.proxies.get(self.config.websockets_proto,None) is not None:
                            kwargs['proxies'] = self.config.waptserver.proxies

                        if not self.socketio_client:
                            self.socketio_client = SocketIO(
                                    host="%s://%s" % (self.config.websockets_proto,self.config.websockets_host),
                                    port=self.config.websockets_port,
                                    Namespace = WaptSocketIORemoteCalls,
                                    verify=self.config.websockets_verify_cert,
                                    wait_for_connection = False,
                                    transport = ['websocket'],
                                    ping_interval = self.config.websockets_ping,
                                    hurry_interval_in_seconds = self.config.websockets_hurry_interval,
                                    params = {'uuid': tmp_wapt.host_uuid,'login':self.config.websockets_auth},
                                    **kwargs)

                            #self.socketio_client.get_namespace().wapt = tmp_wapt


                    if self.socketio_client and self.config.websockets_host:
                        if not self.socketio_client.connected:
                            self.socketio_client._http_session.params.update({'uuid': tmp_wapt.host_uuid,'login':self.config.websockets_auth})
                            self.socketio_client.define(WaptSocketIORemoteCalls)
                            #self.socketio_client.get_namespace().wapt = tmp_wapt
                            self.socketio_client.connect('')
                        if self.socketio_client.connected:
                            logger.info('Socket IO listening for %ss' % self.config.websockets_check_config_interval )
                            self.socketio_client.wait(self.config.websockets_check_config_interval)
                    self.config.reload_if_updated()

                except Exception as e:
                    print('Error in socket io connection %s' % repr(e))
                    self.config.reload_if_updated()
                    if self.socketio_client:
                        print('stop sio client')
                        self.socketio_client._close()
                        del self.socketio_client
                    self.socketio_client = None
                    if self.socketio_client and self.config.websockets_host:
                        self.socketio_client._http_session.params.update({'uuid': tmp_wapt.host_uuid,'login':self.config.websockets_auth})
                    logger.info('Socket IO Stopped, waiting %ss before retrying' % self.config.websockets_retry_delay)
                    time.sleep(self.config.websockets_retry_delay)
开发者ID:tranquilit,项目名称:WAPT,代码行数:63,代码来源:test_socketio_client.py

示例6: SocketIO

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import connect [as 别名]
#!/usr/bin/env python

import os
import sys
import time

if __name__ == '__main__':

    sPath=os.path.dirname(os.path.realpath(__file__))+'/'
    sys.path.append(sPath+'../../../lib/python2.7/site-packages/')

    from socketIO_client import SocketIO

    info = {"id": "26.9604492_38.2381801" ,"country": "TUR", "city" : "Izmir", "longitude" : 26.9604492, "latitude": 38.2381801}
    coordinate = "{ \"id\":\"%s\", \"country\":\"%s\", \"city\":\"%s\", \"x\": %f, \"y\": %f}"\
                 % (info['id'], info['country'], info['city'], info['longitude'], info['latitude'])

    socketIO = SocketIO('127.0.0.1', 80)
    chatSocket = socketIO.connect('/new-event')

    for x in range(0, 100) :
        chatSocket.emit('update', coordinate)
        time.sleep(0.2)
        print coordinate
开发者ID:CyberIntelMafia,项目名称:malwarez,代码行数:26,代码来源:testSocketIO.py

示例7: WaptSocketIOClient

# 需要导入模块: from socketIO_client import SocketIO [as 别名]
# 或者: from socketIO_client.SocketIO import connect [as 别名]
class WaptSocketIOClient(threading.Thread):
    def __init__(self,config_filename = 'c:/wapt/wapt-get.ini',task_manager=None):
        threading.Thread.__init__(self)
        self.name = 'SocketIOClient'
        self.config_filename = config_filename
        self.task_manager = task_manager
        self.config = WaptServiceConfig(config_filename)
        self.socketio_client = None
        self.wapt_remote_calls = None
        self.server_authorization_token = None


    def run(self):
        self.config.reload_if_updated()
        with Wapt(config_filename = self.config.config_filename) as tmp_wapt:
            logger.info('Starting socketio on "%s://%s:%s" ...' % (self.config.websockets_proto,self.config.websockets_host,self.config.websockets_port))
            logger.debug('Certificate checking : %s' %  self.config.websockets_verify_cert)

            def get_connect_params(wapt):
                connect_params = {'uuid': wapt.host_uuid}
                if not self.server_authorization_token:
                    try:
                        self.server_authorization_token = wapt.get_auth_token('websocket')
                        logger.info('Websocket token: %s' % self.server_authorization_token)
                        connect_params['token'] = self.server_authorization_token
                    except Exception as e:
                        logger.warning('Websocket connect params: %s' % e)
                        self.server_authorization_token = None
                return {'params':connect_params,
                        'cert'  :(wapt.get_host_certificate_filename(),wapt.get_host_key_filename())}
            while True:
                try:
                    connect_params = get_connect_params(tmp_wapt)
                    if not self.socketio_client and self.config.websockets_host:
                        logger.debug('Creating socketio client')
                        logger.debug('Proxies : %s'%self.config.waptserver.proxies)
                        # bug in socketio... ? we must not pass proxies at all (even None) if we don"t want to switch to polling mode...
                        kwargs = {}
                        if self.config.waptserver.proxies and self.config.waptserver.proxies.get(self.config.websockets_proto,None) is not None:
                            kwargs['proxies'] = self.config.waptserver.proxies

                        kwargs.update(connect_params)
                        self.socketio_client = SocketIO(
                                host="%s://%s" % (self.config.websockets_proto,self.config.websockets_host),
                                port=self.config.websockets_port,
                                Namespace = WaptSocketIORemoteCalls,
                                resource=self.config.websockets_root,
                                verify=self.config.websockets_verify_cert,
                                wait_for_connection = False,
                                transport = ['websocket'],
                                ping_interval = self.config.websockets_ping,
                                hurry_interval_in_seconds = self.config.websockets_hurry_interval,
                                **kwargs)
                        self.socketio_client.get_namespace().wapt = tmp_wapt
                        self.socketio_client.get_namespace().task_manager = self.task_manager

                    if self.socketio_client and self.config.websockets_host:
                        if not self.socketio_client.connected:
                            self.socketio_client._http_session.update(connect_params)
                            self.socketio_client.define(WaptSocketIORemoteCalls)
                            self.socketio_client.get_namespace().wapt = tmp_wapt
                            self.socketio_client.get_namespace().task_manager = self.task_manager
                            self.socketio_client.connect('')
                        else:
                            # be sure server DB is aware of the current connection.
                            # could be avoided
                            self.socketio_client.emit('wapt_pong')

                        if self.socketio_client.connected:
                            logger.info('Socket IO listening for %ss' % self.config.websockets_check_config_interval )
                            startwait = time.time()
                            self.socketio_client.wait(self.config.websockets_check_config_interval)
                            # QAD workaround for cases where server disconnect but client is between 2 states.
                            # In this case; wait() immediately returns, leading to an indefinite loop eating 1 core.
                            if time.time() - startwait < self.config.websockets_check_config_interval-2:
                                raise Exception('Websocket client seems disconnected. Force Websocket connection to be recreated')

                    elif not self.config.websockets_host:
                        self.socketio_client = None
                        time.sleep(self.config.websockets_retry_delay)
                    else:
                        time.sleep(self.config.websockets_retry_delay)

                    if self.config.reload_if_updated():
                        tmp_wapt.reload_config_if_updated()
                        if self.socketio_client:
                            self.socketio_client.disconnect()
                        raise EWaptException('Configuration changed, force Websocket connection to be recreated')


                except Exception as e:
                    try:
                        # reset token
                        self.server_authorization_token = None
                        self.config.reload_if_updated()
                        if self.socketio_client:
                            self.socketio_client = None
                    finally:
                        logger.debug(u'Exception %s, Socket IO Stopped, waiting %ss before retrying' %
                            (repr(e),self.config.websockets_retry_delay))
#.........这里部分代码省略.........
开发者ID:tranquilit,项目名称:WAPT,代码行数:103,代码来源:waptservice_socketio.py


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