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


Python WebSocketClient.connect方法代码示例

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


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

示例1: WebSocektRFC6455

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
class WebSocektRFC6455(object):

    def __init__(self, url):
        self.ws = WebSocketClient(url)
        self.queue = Queue.Queue()
        def onmessage(m):
            print "received: %s" % m
            self.queue.put(unicode(str(m), 'utf-8'))

        self.ws.received_message = onmessage

    def connect(self):
        self.ws.connect()
        return self

    def send(self, msg):
        self.ws.send(msg)
        return self

    def recv(self, timeout=1.0):
        try:
            return self.queue.get(timeout=timeout)
        except Queue.Empty:
            raise TimeoutException("websocket didn't receive any thing")

    def close(self):
        self.ws.close()
开发者ID:dosht,项目名称:sockjs-protocol,代码行数:29,代码来源:utils_03.py

示例2: skim_test_4_1_2

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
def skim_test_4_1_2(n_topics=10):
    # test 'globals'
    subLock = threading.Lock()
    subscriptions = dict()
    def received_message(m):
        data = json.loads(m.data)
        if data['op'] == 'publish':
            r_topic = data['topic']
            r_msg = json.dumps(data['msg'])

            with subLock:
                for sub in subscriptions.itervalues():
                    if r_topic == sub['topic']:
                        sub['callback'](r_msg)

    ws = WebSocketClient(ROSBRIDGE_HOST)
    ws.received_message = received_message

    ws.connect()

    current_subID = 1
    for i_top in xrange(n_topics):
        # RUN: One Topic (per topic code)
        topicArrived = threading.Event()
        topicArrived.clear()
        def genf(i_topic=0):
            return lambda data: topicArrived.set()

        # Subscribe
        subID = current_subID
        current_subID += 1
        msg = {'op': 'subscribe', 'topic': SUBTOPIC,
               'type': MSGTYPE, 'id': subID, 'throttle_rate': 5}
        ws.send(json.dumps(msg))
        with subLock:
            subscriptions[subID] = {'callback': genf(i_top),
                                    'topic': SUBTOPIC}

        # Wait for Msg
        got_msg = topicArrived.wait(2.0)

        # Unsubscribe
        msg = {'op': 'unsubscribe', 'id': subID, 'topic': SUBTOPIC}
        with subLock:
            del subscriptions[subID]
        ws.send(json.dumps(msg))
        sleep(0.01)  # 0.1 doesn't seem to cause the problem (after 20hr)...

    ws.close()
开发者ID:rethink-rlinsalata,项目名称:test-debug,代码行数:51,代码来源:test_rbc_websocket.py

示例3: test_4_1

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
def test_4_1(n_topics=10):
    if 1:
        ws = WebSocketClient(ROSBRIDGE_HOST)
    else:
        ws = RosBridgeClient(ROSBRIDGE_HOST)
    ws.connect()

    topicArrived = threading.Event()
    for i_top in xrange(n_topics):
        topicArrived.clear()
        def genf(i_topic=0):
            return lambda data: topicArrived.set()

        subID = ws.subscribe(SUBTOPIC, MSGTYPE, genf(i_top))
        got_msg = topicArrived.wait(2.0)
        ws.unsubscribe(subID)

    ws.close()
开发者ID:rethink-rlinsalata,项目名称:test-debug,代码行数:20,代码来源:test_rbc_websocket.py

示例4: killAndRaise

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
def killAndRaise():
    '''
    global php_script_path
    command = 'sudo php ' + php_script_path +'/kill_raise.php ' + str(monitorPID) + ' "python" "' + python_script_path + '/monitor.py"  &'
    print command
    os.system(command)
    '''
    
    global host
    global port
    global ws
    global SOCKET_CONNECTED
    try:
        ws = WebSocketClient('ws://'+host +':'+port+'/')
        ws.connect();
        SOCKET_CONNECTED = True
    except Exception as inst:
        SOCKET_CONNECTED = False
开发者ID:pardoc,项目名称:FAB-UI,代码行数:20,代码来源:monitor.py

示例5: printlog

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
def printlog(percent,num):		
	
	global ws
	global host
	global port
	
	stats = {'percent': str(percent), 'img_number': str(cs), 'tot_images': str(slices)}
	post_processing = {'name':  name, 'pid' : str(myPID), 'started': str(t0), 'completed': str(completed), 'completed_time': str(completed_time), 'stats': stats}
	str_log = {'post_processing': post_processing}
	#str_log='{"post_processing":{"name": "'+name+'","pid": "'+str(myPID)+'","started": "'+str(t0)+'","completed": "'+str(completed)+'","completed_time": "'+str(completed_time)+'","stats":{"percent":"'+str(percent)+'","img_number":'+str(cs)+',"tot_images":'+str(slices)+'}}}'
	message = {'type': 'post_processing', 'data': str_log}
	
	try:
		ws.send(json.dumps(message))
	except Exception, e:
		print str(e)
		ws = WebSocketClient('ws://'+host +':'+port+'/')
		ws.connect();
开发者ID:christopherwit,项目名称:FAB-UI,代码行数:20,代码来源:triangulation.py

示例6: run_gevent

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
def run_gevent():
    from gevent import monkey; monkey.patch_all()
    import gevent
    from ws4py.client.geventclient import WebSocketClient
    
    ws = WebSocketClient('wss://localhost:9000/ws')
    ws.connect()

    ws.send("hello")
    
    def incoming():
        while True:
            m = ws.receive()
            if m is not None:
                print(m)
            else:
                break
            
        ws.close()

    gevent.joinall([gevent.spawn(incoming)])
开发者ID:Lawouach,项目名称:WebSocket-for-Python,代码行数:23,代码来源:bug167_client.py

示例7: test_thread_is_started_once_connected

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
    def test_thread_is_started_once_connected(self, sock):
        s = MagicMock(spec=socket.socket)
        sock.socket.return_value = s
        sock.getaddrinfo.return_value = [(socket.AF_INET, socket.SOCK_STREAM, 0, "",
                                          ("127.0.0.1", 80, 0, 0))]
 
        c = WebSocketClient(url="ws://127.0.0.1/")

        def exchange1(*args, **kwargs):
            yield b"\r\n".join([
                    b"HTTP/1.1 101 Switching Protocols",
                    b"Connection: Upgrade",
                    b"Sec-Websocket-Version: 13",
                    b"Content-Type: text/plain;charset=utf-8",
                    b"Sec-Websocket-Accept: " + b64encode(sha1(c.key + WS_KEY).digest()),
                    b"Upgrade: websocket",
                    b"Date: Sun, 26 Jul 2015 12:32:55 GMT",
                    b"Server: ws4py/test",
                    b"\r\n"
                ])

            for i in range(100):
                time.sleep(0.1)
                yield Frame(opcode=OPCODE_TEXT, body=b'hello',
                            fin=1).build()

        s.recv.side_effect = exchange1()
        self.assertFalse(c._th.is_alive())
        
        c.connect()
        time.sleep(0.5)
        self.assertTrue(c._th.is_alive())

        def exchange2(*args, **kwargs):
            yield Frame(opcode=OPCODE_CLOSE, body=b'',
                        fin=1).build()
        s.recv.side_effect = exchange2()
        time.sleep(0.5)
        self.assertFalse(c._th.is_alive())
开发者ID:Nishida-Lab,项目名称:ROS_with_Choregraphe,代码行数:41,代码来源:test_client.py

示例8: Client

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
class Client(object):
    def __init__(self, listener):
        self.listener = listener
        self._ws_url = 'wss://ws.bitso.com'
        self.ws_client = WebSocketClient(self._ws_url)
        self.ws_client.opened = self.listener.on_connect
        self.ws_client.received_message = self._received
        self.ws_client.closed = self._closed
        self.channels = []

    def connect(self, channels):
        self.channels = channels
        self.ws_client.opened = self._opened
        self.ws_client.connect()
        self.ws_client.run_forever()

    def close(self):
        self.ws_client.close()
        
    def _opened(self):
        for channel in self.channels:
            self.ws_client.send(json.dumps({ 'action': 'subscribe', 'book': 'btc_mxn', 'type': channel }))
        thread.start_new_thread(self._ping_server, ())
        self.listener.on_connect()

    def _received(self, m):
        #print m.data
        val = json.loads(m.data)
        obj = StreamUpdate(val)
        self.listener.on_update(obj)
        
    def _closed(self, code, reason):
        self.listener.on_close(code, reason)
        
    def _ping_server(self):
        while True:
            #keep-alive
            self.ws_client.send(PingControlMessage(u'ping'))
            time.sleep(20)
开发者ID:derektanaka,项目名称:bitso-py,代码行数:41,代码来源:websocket.py

示例9: crd_open_url

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
def crd_open_url(host, url):
    """ Opens URL (developer mode only)

        If your Chromecast device is whitelisted, make
        embedded browser navigate to url."""
    try:
        # ask Chrome debugger interface for api endpoint
        resp = requests.get(FORMAT_DEBUG_URL.format(host))
    except requests.exceptions.ConnectionError:
        return False

    payload = json.loads(resp.text)
    wsurl = payload[0]['webSocketDebuggerUrl']

    # format and send api navigate command to the endpoint
    debugcom = FORMAT_CMD.format(url)
    remws = WebSocketClient(wsurl)
    remws.connect()
    remws.send(debugcom)
    remws.close()

    return True
开发者ID:alandy,项目名称:pychromecast,代码行数:24,代码来源:remotedebug.py

示例10: hack_test_4_1_2

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
def hack_test_4_1_2(n_topics=10):
    # test 'globals'
    subLock = threading.Lock()
    subscriptions = dict()
    def received_message(m):
        data = json.loads(m.data)
        if data['op'] == 'publish':
            r_topic = data['topic']
            r_msg = json.dumps(data['msg'])
#             print data
#             print data.keys()

            with subLock:
                for sub in subscriptions.itervalues():
                    if r_topic == sub['topic']:
                        sub['callback'](r_msg)

    w_type = 2
    if w_type==1:
        ws = WebSocketClient(ROSBRIDGE_HOST)
    elif w_type==2:
        ws = WebSocketClient(ROSBRIDGE_HOST)
        ws.received_message = received_message
#     elif w_type==3:
#         ws = WebSocketClient(ROSBRIDGE_HOST)
#         def received_message(self, m):
#             data = json.loads(m.data)
#             if data['op'] == 'publish':
#                 r_topic = data['topic']
#                 r_msg = json.dumps(data['msg'])
# 
#                 self.subLock.acquire(True)
#                 for sub in self.subscriptions.itervalues():
#                     if r_topic == sub['topic']:
#                         sub['callback'](r_msg)
#                 self.subLock.release()
# #         ws.received_message = received_message
    else:
        ws = RosBridgeClient(ROSBRIDGE_HOST)


    ws.connect()

#     subLock = threading.Lock()
#     subscriptions = dict()
    current_subID = 1
    for i_top in xrange(n_topics):
        # RUN: One Topic (per topic code)
        topicArrived = threading.Event()
        topicArrived.clear()
        def genf(i_topic=0):
            return lambda data: topicArrived.set()

    #     subID = ws.subscribe(SUBTOPIC, MSGTYPE, genf())
        def subscribe(current_subID, topic, messageType, callback):
            subID = current_subID
            current_subID += 1
            msg = {'op': 'subscribe', 'topic': SUBTOPIC,
                   'type': MSGTYPE, 'id': subID, 'throttle_rate': 5}
            ws.send(json.dumps(msg))
            with subLock:
                subscriptions[subID] = {'callback': callback, 'topic': SUBTOPIC}
            return subID
        subID = subscribe(current_subID, SUBTOPIC, MSGTYPE, genf(i_top))

        got_msg = topicArrived.wait(2.0)

    #     ws.unsubscribe(subID)
        def unsubscribe(subID):
            msg = {'op': 'unsubscribe', 'id': subID, 'topic': SUBTOPIC}
            with subLock:
                del subscriptions[subID]
            ws.send(json.dumps(msg))
        unsubscribe(subID)

    ws.close()
开发者ID:rethink-rlinsalata,项目名称:test-debug,代码行数:78,代码来源:test_rbc_websocket.py

示例11: connect

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
 def connect(self, *args, **kwargs):
     self.pre_connect()
     WebSocketClient.connect(self, *args, **kwargs)
     self.connected = True
开发者ID:ftobia,项目名称:sideboard,代码行数:6,代码来源:_websockets.py

示例12: Client

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
class Client(object):
    """Represents a client connection that connects to Discord.
    This class is used to interact with the Discord WebSocket and API.

    A number of options can be passed to the :class:`Client` via keyword arguments.

    :param int max_length: The maximum number of messages to store in :attr:`messages`. Defaults to 5000.

    Instance attributes:

     .. attribute:: user

         A :class:`User` that represents the connected client. None if not logged in.
     .. attribute:: servers

         A list of :class:`Server` that the connected client has available.
     .. attribute:: private_channels

         A list of :class:`PrivateChannel` that the connected client is participating on.
     .. attribute:: messages

        A deque_ of :class:`Message` that the client has received from all servers and private messages.
     .. attribute:: email

        The email used to login. This is only set if login is successful, otherwise it's None.

    .. _deque: https://docs.python.org/3.4/library/collections.html#collections.deque
    """

    def __init__(self, **kwargs):
        self._is_logged_in = False
        self.user = None
        self.email = None
        self.servers = []
        self.private_channels = []
        self.token = ''
        self.messages = deque([], maxlen=kwargs.get('max_length', 5000))
        self.events = {
            'on_ready': _null_event,
            'on_disconnect': _null_event,
            'on_error': _null_event,
            'on_response': _null_event,
            'on_message': _null_event,
            'on_message_delete': _null_event,
            'on_message_edit': _null_event,
            'on_status': _null_event,
            'on_channel_delete': _null_event,
            'on_channel_create': _null_event,
            'on_channel_update': _null_event,
            'on_member_join': _null_event,
            'on_member_remove': _null_event,
            'on_member_update': _null_event,
            'on_server_create': _null_event,
            'on_server_delete': _null_event,
        }

        # the actual headers for the request...
        # we only override 'authorization' since the rest could use the defaults.
        self.headers = {
            'authorization': self.token,
        }

    def _get_message(self, msg_id):
        return utils.find(lambda m: m.id == msg_id, self.messages)

    def _get_server(self, guild_id):
        return utils.find(lambda g: g.id == guild_id, self.servers)

    def _add_server(self, guild):
        guild['roles'] = [Role(**role) for role in guild['roles']]
        members = guild['members']
        owner = guild['owner_id']
        for i, member in enumerate(members):
            roles = member['roles']
            for j, roleid in enumerate(roles):
                role = utils.find(lambda r: r.id == roleid, guild['roles'])
                if role is not None:
                    roles[j] = role
            members[i] = Member(**member)

            # found the member that owns the server
            if members[i].id == owner:
                owner = members[i]

        for presence in guild['presences']:
            user_id = presence['user']['id']
            member = utils.find(lambda m: m.id == user_id, members)
            if member is not None:
                member.status = presence['status']
                member.game_id = presence['game_id']


        server = Server(owner=owner, **guild)

        # give all the members their proper server
        for member in server.members:
            member.server = server

        channels = [Channel(server=server, **channel) for channel in guild['channels']]
        server.channels = channels
#.........这里部分代码省略.........
开发者ID:dsibilly,项目名称:discord.py,代码行数:103,代码来源:client.py

示例13: ThreadedClientTest

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
class ThreadedClientTest(unittest.TestCase):

    @patch('ws4py.client.socket')
    def setUp(self, sock):
        self.sock = MagicMock(spec=socket.socket)
        sock.socket.return_value = self.sock
        sock.getaddrinfo.return_value = [(socket.AF_INET, socket.SOCK_STREAM, 0, "",
                                          ("127.0.0.1", 80, 0, 0))]

        self.client = WebSocketClient(url="ws://127.0.0.1/")

    def _exchange1(self, *args, **kwargs):
        yield b"\r\n".join([
            b"HTTP/1.1 101 Switching Protocols",
            b"Connection: Upgrade",
            b"Sec-Websocket-Version: 13",
            b"Content-Type: text/plain;charset=utf-8",
            b"Sec-Websocket-Accept: " + b64encode(sha1(self.client.key + WS_KEY).digest()),
            b"Upgrade: websocket",
            b"Date: Sun, 26 Jul 2015 12:32:55 GMT",
            b"Server: ws4py/test",
            b"\r\n"
        ])

        for i in range(100):
            time.sleep(0.1)
            yield Frame(opcode=OPCODE_TEXT, body=b'hello',
                        fin=1).build()

    def _exchange2(self, *args, **kwargs):
        yield Frame(opcode=OPCODE_CLOSE, body=b'',
                    fin=1).build()

    def test_thread_is_started_once_connected(self):
        self.sock.recv.side_effect = self._exchange1()
        self.assertFalse(self.client._th.is_alive())

        self.client.connect()
        time.sleep(0.5)
        self.assertTrue(self.client._th.is_alive())

        self.sock.recv.side_effect = self._exchange2()
        time.sleep(0.5)
        self.assertFalse(self.client._th.is_alive())

    def test_thread_is_started_once_connected_secure(self):
        """ Same as the above test, but with SSL socket """
        # pretend the socket is an SSL socket
        self.sock.pending = lambda: False
        self.client._is_secure = True

        self.sock.recv.side_effect = self._exchange1()
        self.assertFalse(self.client._th.is_alive())

        self.client.connect()
        time.sleep(0.5)
        self.assertTrue(self.client._th.is_alive())

        self.sock.recv.side_effect = self._exchange2()
        time.sleep(0.5)
        self.assertFalse(self.client._th.is_alive())
开发者ID:gagaboy,项目名称:WebSocket-for-Python,代码行数:63,代码来源:test_client.py

示例14: connect

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
 def connect(self):
     try:
         return WebSocketClient.connect(self)
     except:
         raise ConnectionError()
开发者ID:Omi-Jiang,项目名称:pydvbcss,代码行数:7,代码来源:__init__.py

示例15: Client

# 需要导入模块: from ws4py.client.threadedclient import WebSocketClient [as 别名]
# 或者: from ws4py.client.threadedclient.WebSocketClient import connect [as 别名]
class Client(object):
    """Represents a client connection that connects to Discord.
    This class is used to interact with the Discord WebSocket and API.

    A number of options can be passed to the :class:`Client` via keyword arguments.

    :param int max_length: The maximum number of messages to store in :attr:`messages`. Defaults to 5000.

    Instance attributes:

     .. attribute:: user

         A :class:`User` that represents the connected client. None if not logged in.
     .. attribute:: servers

         A list of :class:`Server` that the connected client has available.
     .. attribute:: private_channels

         A list of :class:`PrivateChannel` that the connected client is participating on.
     .. attribute:: messages

        A deque_ of :class:`Message` that the client has received from all servers and private messages.

    .. _deque: https://docs.python.org/3.4/library/collections.html#collections.deque
    """

    def __init__(self, **kwargs):
        self._is_logged_in = False
        self.user = None
        self.servers = []
        self.private_channels = []
        self.token = ''
        self.messages = deque([], maxlen=kwargs.get('max_length', 5000))
        self.events = {
            'on_ready': _null_event,
            'on_disconnect': _null_event,
            'on_error': _null_event,
            'on_response': _null_event,
            'on_message': _null_event,
            'on_message_delete': _null_event
        }

        self.ws = WebSocketClient(endpoints.WEBSOCKET_HUB, protocols=['http-only', 'chat'])

        # this is kind of hacky, but it's to avoid deadlocks.
        # i.e. python does not allow me to have the current thread running if it's self
        # it throws a 'cannot join current thread' RuntimeError
        # So instead of doing a basic inheritance scheme, we're overriding the member functions.

        self.ws.opened = self._opened
        self.ws.closed = self._closed
        self.ws.received_message = self._received_message
        self.ws.connect()

        # the actual headers for the request...
        # we only override 'authorization' since the rest could use the defaults.
        self.headers = {
            'authorization': self.token,
        }

    def _received_message(self, msg):
        response = json.loads(str(msg))
        if response.get('op') != 0:
            return

        self.events['on_response'](response)
        event = response.get('t')
        data = response.get('d')

        if event == 'READY':
            self.user = User(**data['user'])
            guilds = data.get('guilds')

            for guild in guilds:
                guild['roles'] = [role.get('name') for role in guild['roles']]
                guild['members'] = [User(**member['user']) for member in guild['members']]

                self.servers.append(Server(**guild))
                channels = [Channel(server=self.servers[-1], **channel) for channel in guild['channels']]
                self.servers[-1].channels = channels

            for pm in data.get('private_channels'):
                self.private_channels.append(PrivateChannel(id=pm['id'], user=User(**pm['recipient'])))

            # set the keep alive interval..
            self.ws.heartbeat_freq = data.get('heartbeat_interval')

            # we're all ready
            self.events['on_ready']()
        elif event == 'MESSAGE_CREATE':
            channel = self.get_channel(data.get('channel_id'))
            message = Message(channel=channel, **data)
            self.events['on_message'](message)
            self.messages.append(message)
        elif event == 'MESSAGE_DELETE':
            channel = self.get_channel(data.get('channel_id'))
            message_id = data.get('id')
            found = next((m for m in self.messages if m.id == message_id), None)
            if found is not None:
                self.events['on_message_delete'](found)
#.........这里部分代码省略.........
开发者ID:Luigifan,项目名称:pydiscord,代码行数:103,代码来源:client.py


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