當前位置: 首頁>>代碼示例>>Python>>正文


Python Stream.text_message方法代碼示例

本文整理匯總了Python中ws4py.streaming.Stream.text_message方法的典型用法代碼示例。如果您正苦於以下問題:Python Stream.text_message方法的具體用法?Python Stream.text_message怎麽用?Python Stream.text_message使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ws4py.streaming.Stream的用法示例。


在下文中一共展示了Stream.text_message方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_helper_with_bytes_text_message

# 需要導入模塊: from ws4py.streaming import Stream [as 別名]
# 或者: from ws4py.streaming.Stream import text_message [as 別名]
 def test_helper_with_bytes_text_message(self):
     s = Stream()
     m = s.text_message('hello there!')
     self.assertIsInstance(m, TextMessage)
     self.assertFalse(m.is_binary)
     self.assertTrue(m.is_text)
     self.assertEqual(m.opcode, OPCODE_TEXT)
     self.assertEqual(m.encoding, 'utf-8')
     self.assertIsInstance(m.data, bytes)
     self.assertEqual(len(m), 12)
     self.assertEqual(len(m.data), 12)
     self.assertEqual(m.data, b'hello there!')
開發者ID:17dakmue,項目名稱:WebSocket-for-Python,代碼行數:14,代碼來源:test_stream.py

示例2: WebSocketHandler

# 需要導入模塊: from ws4py.streaming import Stream [as 別名]
# 或者: from ws4py.streaming.Stream import text_message [as 別名]

#.........這裏部分代碼省略.........
            pass

    def ponged(self, pong):
        """
        Pong message received on the stream.

        @param pong: messaging.PongControlMessage instance
        """
        pass

    def received_message(self, m):
        """
        Message received on the stream.

        @param pong: messaging.TextMessage or messaging.BinaryMessage instance
        """
        pass

    def send(self, payload, binary=False):
        """
        Sends the given payload out.

        If payload is some bytes or a bytearray,
        then it is sent as a single message not fragmented.

        If payload is a generator, each chunk is sent as part of
        fragmented message.

        @param payload: string, bytes, bytearray or a generator
        @param binary: if set, handles the payload as a binary message
        """
        if isinstance(payload, basestring) or isinstance(payload, bytearray):
            if not binary:
                self.write_to_connection(self.stream.text_message(payload).single())
            else:
                self.write_to_connection(self.stream.binary_message(payload).single())
                
        elif type(payload) == types.GeneratorType:
            bytes = payload.next()
            first = True
            for chunk in payload:
                if not binary:
                    self.write_to_connection(self.stream.text_message(bytes).fragment(first=first))
                else:
                    self.write_to_connection(self.stream.binary_message(payload).fragment(first=first))
                bytes = chunk
                first = False
            if not binary:
                self.write_to_connection(self.stream.text_message(bytes).fragment(last=True))
            else:
                self.write_to_connection(self.stream.text_message(bytes).fragment(last=True))

    def _receive(self):
        """
        Performs the operation of reading from the underlying
        connection in order to feed the stream of bytes.

        We start with a small size of two bytes to be read
        from the connection so that we can quickly parse an
        incoming frame header. Then the stream indicates
        whatever size must be read from the connection since
        it knows the frame payload length.

        Note that we perform some automatic opererations:

        * On a closing message, we respond with a closing
開發者ID:baoming,項目名稱:WebSocket-for-Python,代碼行數:70,代碼來源:threadedhandler.py

示例3: WebSocketBaseClient

# 需要導入模塊: from ws4py.streaming import Stream [as 別名]
# 或者: from ws4py.streaming.Stream import text_message [as 別名]

#.........這裏部分代碼省略.........
    def handshake_request(self):
        parts = urlsplit(self.url)
        
        headers = self.handshake_headers
        request = ["GET %s HTTP/1.1" % parts.path]
        for header, value in headers:
            request.append("%s: %s" % (header, value))
        request.append('\r\n')

        return '\r\n'.join(request)

    def process_response_line(self, response_line):
        protocol, code, status = response_line.split(' ', 2)
        if code != '101':
            raise HandshakeError("Invalid response status: %s %s" % (code, status))

    def process_handshake_header(self, headers):
        protocols = []
        extensions = []

        headers = headers.strip()
        
        for header_line in headers.split('\r\n'):
            header, value = header_line.split(':', 1)
            header = header.strip().lower()
            value = value.strip().lower()
            
            if header == 'upgrade' and value != 'websocket':
                raise HandshakeError("Invalid Upgrade header: %s" % value)

            elif header == 'connection' and value != 'upgrade':
                raise HandshakeError("Invalid Connection header: %s" % value)

            elif header == 'sec-websocket-accept':
                match = b64encode(sha1(self.key + WS_KEY).digest())
                if value != match.lower():
                    raise HandshakeError("Invalid challenge response: %s" % value)

            elif header == 'sec-websocket-protocol':
                protocols = ','.join(value)

            elif header == 'sec-websocket-extensions':
                extensions = ','.join(value)

        return protocols, extensions

    def opened(self, protocols, extensions):
        pass

    def received_message(self, m):
        pass

    def closed(self, code, reason=None):
        pass

    @property
    def terminated(self):
        return self.client_terminated is True and self.server_terminated is True
    
    def close(self, reason='', code=1000):
        if not self.client_terminated:
            self.client_terminated = True
            self.write_to_connection(self.stream.close(code=code, reason=reason))

    def connect(self):
        raise NotImplemented()

    def write_to_connection(self, bytes):
        raise NotImplemented()

    def read_from_connection(self, amount):
        raise NotImplemented()

    def close_connection(self):
        raise NotImplemented()
               
    def send(self, payload, binary=False):
        if isinstance(payload, basestring):
            if not binary:
                self.write_to_connection(self.stream.text_message(payload).single(mask=True))
            else:
                self.write_to_connection(self.stream.binary_message(payload).single(mask=True))
        
        elif isinstance(payload, dict):
            self.write_to_connection(self.stream.text_message(json.dumps(payload)).single(mask=True))
        
        elif type(payload) == types.GeneratorType:
            bytes = payload.next()
            first = True
            for chunk in payload:
                if not binary:
                    self.write_to_connection(self.stream.text_message(bytes).fragment(first=first, mask=True))
                else:
                    self.write_to_connection(self.stream.binary_message(payload).fragment(first=first, mask=True))
                bytes = chunk
                first = False
            if not binary:
                self.write_to_connection(self.stream.text_message(bytes).fragment(last=True, mask=True))
            else:
                self.write_to_connection(self.stream.text_message(bytes).fragment(last=True, mask=True))
開發者ID:EmadAlblueshi,項目名稱:vertx-web,代碼行數:104,代碼來源:__init__.py

示例4: WebSocket

# 需要導入模塊: from ws4py.streaming import Stream [as 別名]
# 或者: from ws4py.streaming.Stream import text_message [as 別名]
class WebSocket(object):
    def __init__(self, sock, environ, protocols=None, extensions=None):
        self.stream = Stream()

        self.protocols = protocols
        self.extensions = extensions
        self.environ = environ

        self.sock = sock
        self.sock.settimeout(30.0)

        self.client_terminated = False
        self.server_terminated = False

        self._lock = Semaphore()

    def close(self, code=1000, reason=''):
        """
        Call this method to initiate the websocket connection
        closing by sending a close frame to the connected peer.

        Once this method is called, the server_terminated
        attribute is set. Calling this method several times is
        safe as the closing frame will be sent only the first
        time.

        @param code: status code describing why the connection is closed
        @param reason: a human readable message describing why the connection is closed
        """
        if not self.server_terminated:
            self.server_terminated = True
            self.write_to_connection(self.stream.close(code=code, reason=reason))
        self.close_connection()

    @property
    def terminated(self):
        """
        Returns True if both the client and server have been
        marked as terminated.
        """
        return self.client_terminated is True and self.server_terminated is True

    def write_to_connection(self, bytes):
        """
        Writes the provided bytes to the underlying connection.

        @param bytes: data tio send out
        """
        return self.sock.sendall(bytes)

    def read_from_connection(self, amount):
        """
        Reads bytes from the underlying connection.

        @param amount: quantity to read (if possible)
        """
        return self.sock.recv(amount)

    def close_connection(self):
        """
        Shutdowns then closes the underlying connection.
        """
        try:
            self.sock.shutdown(socket.SHUT_RDWR)
        finally:
            self.sock.close()

    def send(self, payload, binary=False):
        """
        Sends the given payload out.

        If payload is some bytes or a bytearray,
        then it is sent as a single message not fragmented.

        If payload is a generator, each chunk is sent as part of
        fragmented message.

        @param payload: string, bytes, bytearray or a generator
        @param binary: if set, handles the payload as a binary message
        """
        if isinstance(payload, basestring) or isinstance(payload, bytearray):
            if not binary:
                self.write_to_connection(self.stream.text_message(payload).single())
            else:
                self.write_to_connection(self.stream.binary_message(payload).single())

        elif type(payload) == types.GeneratorType:
            bytes = payload.next()
            first = True
            for chunk in payload:
                if not binary:
                    self.write_to_connection(self.stream.text_message(bytes).fragment(first=first))
                else:
                    self.write_to_connection(self.stream.binary_message(payload).fragment(first=first))
                bytes = chunk
                first = False
            if not binary:
                self.write_to_connection(self.stream.text_message(bytes).fragment(last=True))
            else:
                self.write_to_connection(self.stream.text_message(bytes).fragment(last=True))
#.........這裏部分代碼省略.........
開發者ID:UNIVERSAL-IT-SYSTEMS,項目名稱:stargate-1,代碼行數:103,代碼來源:view.py


注:本文中的ws4py.streaming.Stream.text_message方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。