Python websocket 模块,WebSocketTimeoutException() 实例源码

我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用websocket.WebSocketTimeoutException()

项目:Treehacks    作者:andrewsy97    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:Treehacks    作者:andrewsy97    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.recv()
项目:Treehacks    作者:andrewsy97    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:Treehacks    作者:andrewsy97    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.recv()
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
def _trade_thread(self):
        try:
            conn = create_connection(self.trader_addr)
        except Exception:
            log.exception('Trader Thread Error!')
            self._controller_q.put('restart_trader')
            return

        while self.running:
            try:
                data = conn.recv()
            except WebSocketTimeoutException:
                self._controller_q.put('restart_data')
                return
            self.data_q.put(json.loads(data))

            try:
                payload = self.trade_command_q.get()
            except Empty:
                continue

            try:
                conn.send(self.sign(payload))
            except (WebSocketTimeoutException, ConnectionResetError):
                continue
项目:tk-photoshopcc    作者:shotgunsoftware    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:tk-photoshopcc    作者:shotgunsoftware    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.recv()
项目:siphon-cli    作者:getsiphon    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:siphon-cli    作者:getsiphon    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.recv()
项目:cmdchallenge-site    作者:jarv    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1)
项目:cmdchallenge-site    作者:jarv    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv()
项目:chromeremote    作者:sadnoodles    | 项目源码 | 文件源码
def messages(self, auto_handle_message=True, timeout_return_none=False):
        self.start_time = time.time()
        self.check_ws_ready()
        while self._running:

            # check tab max timeout
            now = time.time()
            if now - self.start_time > self.TAB_TIMEOUT:
                raise TabTimeout()

            try:
                message = self.ws.recv()
                parsed_message = json.loads(message)
                if auto_handle_message:
                    self.handle_messages(parsed_message)
                yield parsed_message
            except websocket.WebSocketTimeoutException:
                if timeout_return_none:
                    yield None
                continue
            except websocket.WebSocketConnectionClosedException:
                break
            except KeyboardInterrupt:
                break
项目:chrome_remote_interface_python    作者:wasiher    | 项目源码 | 文件源码
def recv(self):
        n = 0
        self._soc.settimeout(0.1)
        try:
            got = self._soc.recv()
            while 1:
                try:
                    val = json.loads(got)
                    self._handle_event(val['method'], val['params'])
                    n += 1
                    break
                except json.JSONDecodeError as e:
                    self._handle_event(got[:e.pos])
                    n += 1
                    got = got[e.pos:]
        except websocket.WebSocketTimeoutException:
            pass
        self._soc.settimeout(None)
        return n
项目:Flask-SocketIO    作者:cutedogspark    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:Flask-SocketIO    作者:cutedogspark    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.recv()
项目:pychrome    作者:fate0    | 项目源码 | 文件源码
def _recv_loop(self):
        while not self._stopped.is_set():
            try:
                self._ws.settimeout(1)
                message_json = self._ws.recv()
                message = json.loads(message_json)
            except websocket.WebSocketTimeoutException:
                continue
            except (websocket.WebSocketException, OSError):
                if not self._stopped.is_set():
                    logger.error("websocket exception", exc_info=True)
                    self._stopped.set()
                return

            if self.debug:  # pragma: no cover
                print('< RECV %s' % message_json)

            if "method" in message:
                self.event_queue.put(message)

            elif "id" in message:
                if message["id"] in self.method_results:
                    self.method_results[message['id']].put(message)
            else:  # pragma: no cover
                warnings.warn("unknown message: %s" % message)
项目:spacy-nlp    作者:kengz    | 项目源码 | 文件源码
def recv_packet_unicode(self):
    try:
        packet_text = self._connection.recv()
    except websocket.WebSocketTimeoutException as e:
        raise TimeoutError('recv timed out (%s)' % e)
    except websocket.SSLError as e:
        raise ConnectionError('recv disconnected by SSL (%s)' % e)
    except websocket.WebSocketConnectionClosedException as e:
        raise ConnectionError('recv disconnected (%s)' % e)
    except socket.error as e:
        raise ConnectionError('recv disconnected (%s)' % e)
    try:
        encoded = six.b(packet_text)
    except (UnicodeEncodeError):
        pass
    else:
        encoded = six.u(packet_text)
    engineIO_packet_type, engineIO_packet_data = parse_packet_text(encoded)
    yield engineIO_packet_type, engineIO_packet_data

# Set the new recv_packet_unicode method
项目:smileybot    作者:sillylyn    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:smileybot    作者:sillylyn    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.recv()
项目:bitcoinelasticsearch    作者:currentsea    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:bitcoinelasticsearch    作者:currentsea    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.recv()
项目:bitcoinelasticsearch    作者:currentsea    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:bitcoinelasticsearch    作者:currentsea    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.recv()
项目:bitcoinelasticsearch    作者:currentsea    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            data = sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            data = sock.frame_buffer.recv_strict(1)
项目:deb-python-websocket-client    作者:openstack    | 项目源码 | 文件源码
def testInternalRecvStrict(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("foo"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("bar"))
        # s.add_packet(SSLError("The read operation timed out"))
        s.add_packet(six.b("baz"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.frame_buffer.recv_strict(9)
        # if six.PY2:
        #     with self.assertRaises(ws.WebSocketTimeoutException):
        #         data = sock._recv_strict(9)
        # else:
        #     with self.assertRaises(SSLError):
        #         data = sock._recv_strict(9)
        data = sock.frame_buffer.recv_strict(9)
        self.assertEqual(data, six.b("foobarbaz"))
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.frame_buffer.recv_strict(1)
项目:deb-python-websocket-client    作者:openstack    | 项目源码 | 文件源码
def testRecvTimeout(self):
        sock = ws.WebSocket()
        s = sock.sock = SockMock()
        s.add_packet(six.b("\x81"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x8dabcd\x29\x07\x0f\x08\x0e"))
        s.add_packet(socket.timeout())
        s.add_packet(six.b("\x4e\x43\x33\x0e\x10\x0f\x00\x40"))
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        with self.assertRaises(ws.WebSocketTimeoutException):
            sock.recv()
        data = sock.recv()
        self.assertEqual(data, "Hello, World!")
        with self.assertRaises(ws.WebSocketConnectionClosedException):
            sock.recv()
项目:enterprise_gateway    作者:jupyter-incubator    | 项目源码 | 文件源码
def test_cell(nb_test_case, ws, code_cell, code_cell_count):
        print("\n--- {}) {}\n{}".format(code_cell_count, code_cell,
                                      code_cell.get_source_for_execution()))
        code_source = code_cell.get_source_for_execution()
        ws.send(ElyraClient.new_code_message(code_source))
        target_queue = code_cell.get_target_output_type_queue()
        if code_cell.is_output_empty():
            # If output empty, waiting for "execute_input" type message
            target_queue = deque(["execute_input"])
        try:
            json_output_message = ElyraClient.receive_target_messages(ws, target_queue)
        except websocket.WebSocketTimeoutException as wste:
            print("Fail ===================================\nRequest timed out.")
            return 1
        except Exception as e:
            print("FATAL ===================================\n{}.".format(e))
            raise e

        result_cell = NBCodeCell(message_json_list=json_output_message)
        return NBCodeEntity.compare_results(nb_test_case, code_cell, result_cell)
项目:ChromeHeadlessInterface    作者:wilson9x1    | 项目源码 | 文件源码
def recv_until_string(self, expected_string):

        ws_result = []
        ws_instance = self._tab.get("ws_instance")

        while True:
            try:
                result = ws_instance.recv()
            except websocket.WebSocketTimeoutException:
                return ws_result

            if self._debug:
                print("[DEBUG] result: {0}".format(result))
            if not result:
                return ws_result

            # ????
            ws_result.append(result)

            # ?????????
            formatted_result = json.loads(result)
            event_name = formatted_result.get("method")
            params = formatted_result.get("params")
            self._call_event_listener(event_name, params)

            # ??????
            if expected_string in result:
                break
        return ws_result
项目:ChromeHeadlessInterface    作者:wilson9x1    | 项目源码 | 文件源码
def recv_by_special_id(self, command_id=None):

        if command_id:
            expected_id = command_id
        else:
            expected_id = self._command_id

        ws_result = []
        ws_instance = self._tab.get("ws_instance")

        while True:
            try:
                result = ws_instance.recv()
            except websocket.WebSocketTimeoutException:
                return ws_result

            if self._debug:
                print("[DEBUG] result: {0}".format(result))
            if not result:
                return ws_result

            # ????
            ws_result.append(result)

            # ?????????
            formatted_result = json.loads(result)
            event_name = formatted_result.get("method")
            params = formatted_result.get("params")
            self._call_event_listener(event_name, params)

            # ??????
            if int(formatted_result.get("id", 0)) == expected_id-1:
                break
        return ws_result
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
def _process_data(self):
        self.conn = create_connection(self.addr, timeout=4)
        for pair in self.pairs:
            payload = [{'event': 'addChannel',
                        'channel': 'ok_sub_spotusd_%s_ticker' % pair},
                       {'event': 'addChannel',
                        'channel': 'ok_sub_spotusd_%s_depth_60' % pair},
                       {'event': 'addChannel',
                        'channel': 'ok_sub_spotusd_%s_trades' % pair},
                       {'event': 'addChannel',
                        'channel': 'ok_sub_spotusd_%s_kline_1min' % pair}]
            log.debug(payload)
            self.conn.send(json.dumps(payload))
        while self.running:
            try:
                data = json.loads(self.conn.recv())
            except (WebSocketTimeoutException, ConnectionResetError):
                self._controller_q.put('restart')

            if 'data' in data:
                pair = ''.join(data['channel'].split('spot')[1].split('_')[:2]).upper()
                self.data_q.put((data['channel'], pair, data['data'],
                                 time.time()))
            else:
                log.debug(data)
        self.conn = None
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
def _process_data(self):
        self.conn = create_connection(self.addr, timeout=4)
        payload = json.dumps({'type': 'subscribe', 'product_ids': self.pairs})
        self.conn.send(payload)
        while self.running:
            try:
                data = json.loads(self.conn.recv())
            except (WebSocketTimeoutException, ConnectionResetError):
                self._controller_q.put('restart')

            if 'product_id' in data:
                self.data_q.put(('order_book', data['product_id'],
                                 data, time.time()))
        self.conn = None
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
def start(self):
        """
        Start the websocket client threads
        :return:
        """
        super(BitfinexWSS, self).start()

        log.info("BitfinexWSS.start(): Initializing Websocket connection..")
        while self.conn is None:
            try:
                self.conn = create_connection(self.addr, timeout=10)
            except WebSocketTimeoutException:
                self.conn = None
                print("Couldn't create websocket connection - retrying!")

        log.info("BitfinexWSS.start(): Initializing receiver thread..")
        if not self.receiver_thread:
            self.receiver_thread = Thread(target=self.receive, name='Receiver Thread')
            self.receiver_thread.start()
        else:
            log.info("BitfinexWSS.start(): Thread not started! "
                     "self.receiver_thread is populated!")

        log.info("BitfinexWSS.start(): Initializing processing thread..")
        if not self.processing_thread:
            self.processing_thread = Thread(target=self.process, name='Processing Thread')
            self.processing_thread.start()
        else:
            log.info("BitfinexWSS.start(): Thread not started! "
                     "self.processing_thread is populated!")

        self.setup_subscriptions()
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
def receive(self):
        """
        Receives incoming websocket messages, and puts them on the Client queue
        for processing.
        :return:
        """
        while self.running:
            if self._receiver_lock.acquire(blocking=False):
                try:
                    raw = self.conn.recv()
                except WebSocketTimeoutException:
                    self._receiver_lock.release()
                    continue
                except WebSocketConnectionClosedException:
                    # this needs to restart the client, while keeping track
                    # of the currently subscribed channels!
                    self.conn = None
                    self._controller_q.put('restart')
                except AttributeError:
                    # self.conn is None, idle loop until shutdown of thread
                    self._receiver_lock.release()
                    continue
                msg = time.time(), json.loads(raw)
                log.debug("receiver Thread: Data Received: %s", msg)
                self.receiver_q.put(msg)
                self._receiver_lock.release()
            else:
                # The receiver_lock was locked, idling until available
                time.sleep(0.5)
项目:bitex    作者:nlsdfnbch    | 项目源码 | 文件源码
def _subscription_thread(self, endpoint):
        """
        Thread Method, running the connection for each endpoint.
        :param endpoint:
        :return:
        """
        try:
            conn = create_connection(self.addr + endpoint, timeout=5)
        except WebSocketTimeoutException:
            self.restart_q.put(endpoint)
            return

        while self.threads_running[endpoint]:
            try:
                msg = conn.recv()
            except WebSocketTimeoutException:
                self._controller_q.put(endpoint)

            log.debug("%s, %s", endpoint, msg)
            ep, pair = endpoint.split('/')
            log.debug("_subscription_thread(): Putting data on q..")
            try:
                self.data_q.put((ep, pair, msg, time.time()), timeout=1)
            except TimeoutError:
                continue
            finally:
                log.debug("_subscription_thread(): Data Processed, looping back..")
        conn.close()
        log.debug("_subscription_thread(): Thread Loop Ended.")
项目:falsy    作者:pingf    | 项目源码 | 文件源码
def run1(self, payload):
        data = None
        browser = None
        begin_time = datetime.datetime.now()
        retry = payload.get('retried', False)
        try:
            socket_timeout = payload.get('sockettimeout') or self._socket_timeout
            browser = websocket.create_connection(self._browser_url, timeout=socket_timeout)
            data = self.run1_core(payload, browser, begin_time)
            return data
        except websocket.WebSocketTimeoutException as e:
            if retry:
                error_data = {
                    'state': 'critical',
                    'error_code': -6,
                    'error_desc': str(type(e)) + ': ' + str(e)
                }
                ret = self.crawl_info(error_data, payload, begin_time)
                return ret
            else:
                sleep(payload.get('retry_sleep', 3))
                payload['sockettimeout'] = int(payload.get('sockettimeout') or self._socket_timeout) + payload.get(
                    'retry_extra', 10)
                payload['loadtimeout'] = int(payload.get('loadtimeout') or self._socket_timeout) + payload.get('retry_extra',
                                                                                                               10)
                payload['retried'] = True
                return self.run1_core(payload, browser=browser, begin_time=begin_time)
        except Exception as e:
            error_data = {
                'state': 'critical',
                'error_code': -7,
                'error_desc': str(type(e)) + ': ' + str(e)
            }
            ret = self.crawl_info(error_data, payload, begin_time)
            return ret

        finally:
            if browser is not None:
                browser.close()
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def _ws_events(ws_conn, message, snapshot, since, on_message, on_error):
    """Process websocket events."""
    # Pylint complains too many nested blocks.
    #
    # pylint: disable=R0101
    last_timestamp = since
    subscription_msg = {'since': since,
                        'snapshot': snapshot}
    subscription_msg.update(message)

    try:
        ws_conn.send(json.dumps(subscription_msg))
        while True:
            try:
                reply = ws_conn.recv()
                if not reply:
                    break

                result = json.loads(reply)
                if '_error' in result:
                    if on_error:
                        on_error(result)
                    break

                last_timestamp = result.get('when', time.time())
                if on_message:
                    if not on_message(result):
                        break
            except ws_client.WebSocketTimeoutException:
                ws_conn.ping()

    except ws_client.WebSocketConnectionClosedException as err:
        _LOGGER.debug('ws connection closed, will retry: %s.', str(err))
        raise _RetryError(last_timestamp)
    finally:
        ws_conn.close()
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def ws_loop(wsapi, message, snapshot, on_message, on_error=None,
            timeout=_DEFAULT_TIMEOUT):
    """Instance trace loop."""
    ws_conn = None
    since = 0

    while True:
        apis = context.GLOBAL.ws_api(wsapi)
        for api in apis:

            try:
                _LOGGER.debug('Connecting to %s, [timeout: %s]', api, timeout)
                ws_conn = ws_client.create_connection(api, timeout=timeout)
                _LOGGER.debug('Connected.')

                return _ws_events(ws_conn, message, snapshot, since,
                                  on_message, on_error)
            except ws_client.WebSocketTimeoutException as to_err:
                _LOGGER.debug('Connection timeout: %s, %s', api, str(to_err))
                continue
            except ws_client.WebSocketProxyException as proxy_err:
                _LOGGER.debug('Websocket connection error: %s, %s', api,
                              str(proxy_err))
                continue
            except socket.error:
                _LOGGER.debug('Connection failed: %s', api)
                continue
            except _RetryError as retry_err:
                since = retry_err.since

        if not ws_conn:
            raise WSConnectionError()
项目:Flask-SocketIO    作者:cutedogspark    | 项目源码 | 文件源码
def recv_packet(self):
        try:
            packet_text = self._connection.recv()
        except websocket.WebSocketTimeoutException as e:
            raise TimeoutError('recv timed out (%s)' % e)
        except websocket.SSLError as e:
            raise ConnectionError('recv disconnected by SSL (%s)' % e)
        except websocket.WebSocketConnectionClosedException as e:
            raise ConnectionError('recv disconnected (%s)' % e)
        except socket.error as e:
            raise ConnectionError('recv disconnected (%s)' % e)
        engineIO_packet_type, engineIO_packet_data = parse_packet_text(
            six.b(packet_text))
        yield engineIO_packet_type, engineIO_packet_data
项目:Flask-SocketIO    作者:cutedogspark    | 项目源码 | 文件源码
def send_packet(self, engineIO_packet_type, engineIO_packet_data=''):
        packet = format_packet_text(engineIO_packet_type, engineIO_packet_data)
        try:
            self._connection.send(packet)
        except websocket.WebSocketTimeoutException as e:
            raise TimeoutError('send timed out (%s)' % e)
        except socket.error as e:
            raise ConnectionError('send disconnected (%s)' % e)
        except websocket.WebSocketConnectionClosedException as e:
            raise ConnectionError('send disconnected (%s)' % e)