ws4py Package

ws4py Package

exc Module

exception ws4py.exc.WebSocketException[source]

Bases: exceptions.Exception

exception ws4py.exc.FrameTooLargeException[source]

Bases: ws4py.exc.WebSocketException

exception ws4py.exc.ProtocolException[source]

Bases: ws4py.exc.WebSocketException

exception ws4py.exc.UnsupportedFrameTypeException[source]

Bases: ws4py.exc.WebSocketException

exception ws4py.exc.TextFrameEncodingException[source]

Bases: ws4py.exc.WebSocketException

exception ws4py.exc.UnsupportedFrameTypeException[source]

Bases: ws4py.exc.WebSocketException

exception ws4py.exc.TextFrameEncodingException[source]

Bases: ws4py.exc.WebSocketException

exception ws4py.exc.StreamClosed[source]

Bases: exceptions.Exception

exception ws4py.exc.HandshakeError(msg)[source]

Bases: ws4py.exc.WebSocketException

exception ws4py.exc.InvalidBytesError[source]

Bases: ws4py.exc.WebSocketException

framing Module

class ws4py.framing.Frame(opcode=None, body='', masking_key=None, fin=0, rsv1=0, rsv2=0, rsv3=0)[source]

Bases: object

Implements the framing protocol as defined by RFC 6455.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> test_mask = 'XXXXXX' # perhaps from os.urandom(4)
>>> f = Frame(OPCODE_TEXT, 'hello world', masking_key=test_mask, fin=1) 
>>> bytes = f.build()
>>> bytes.encode('hex')
'818bbe04e66ad6618a06d1249105cc6882'
>>> f = Frame()
>>> f.parser.send(bytes[0])
1
>>> f.parser.send(bytes[1])
4
build()[source]

Builds a frame from the instance’s attributes and returns its bytes representation.

mask(data)[source]

Performs the masking or unmasking operation on data using the simple masking algorithm:

unmask(data)

Performs the masking or unmasking operation on data using the simple masking algorithm:

parser[source]

messaging Module

class ws4py.messaging.Message(opcode, data='', encoding='utf-8')[source]

Bases: object

A message is a application level entity. It’s usually built from one or many frames. The protocol defines several kind of messages which are grouped into two sets:

  • data messages which can be text or binary typed
  • control messages which provide a mechanism to perform in-band control communication between peers

The opcode indicates the message type and data is the possible message payload.

The payload is held internally as a a bytearray() as they are faster than pure strings for append operations.

Unicode data will be encoded using the provided encoding.

extend(data)[source]

Add more data to the message.

fragment(first=False, last=False, mask=False)[source]

Returns a ws4py.framing.Frame bytes.

The behavior depends on the given flags:

  • first: the frame uses self.opcode else a continuation opcode
  • last: the frame has its fin bit set
  • mask: the frame is masked using a automatically generated 4-byte token
single(mask=False)[source]

Returns a frame bytes with the fin bit set and a random mask.

If mask is set, automatically mask the frame using a generated 4-byte token.

completed[source]

Indicates the the message is complete, meaning the frame’s fin bit was set.

class ws4py.messaging.TextMessage(text=None)[source]

Bases: ws4py.messaging.Message

is_binary[source]
is_text[source]
class ws4py.messaging.BinaryMessage(bytes=None)[source]

Bases: ws4py.messaging.Message

is_binary[source]
is_text[source]
class ws4py.messaging.CloseControlMessage(code=1000, reason='')[source]

Bases: ws4py.messaging.Message

class ws4py.messaging.PingControlMessage(data=None)[source]

Bases: ws4py.messaging.Message

class ws4py.messaging.PongControlMessage(data)[source]

Bases: ws4py.messaging.Message

streaming Module

class ws4py.streaming.Stream(always_mask=False, expect_masking=True)[source]

Bases: object

Represents a websocket stream of bytes flowing in and out.

The stream doesn’t know about the data provider itself and doesn’t even know about sockets. Instead the stream simply yields for more bytes whenever it requires them. The stream owner is responsible to provide the stream with those bytes until a frame can be interpreted.

1
2
3
4
5
6
7
8
9
>>> s = Stream()
>>> s.parser.send(BYTES)
>>> s.has_messages
False
>>> s.parser.send(MORE_BYTES)
>>> s.has_messages
True
>>> s.message
<TextMessage ... >

Set always_mask to mask all frames built.

Set expect_masking to indicate masking will be checked on all parsed frames.

binary_message(bytes)[source]

Returns a ws4py.messaging.BinaryMessage instance ready to be built. Convenience method so that the caller doesn’t need to import the ws4py.messaging.BinaryMessage class itself.

close(code=1000, reason='')[source]

Returns a close control message built from a ws4py.messaging.CloseControlMessage instance, using the given status code and reason message.

ping(data='')[source]

Returns a ping control message built from a ws4py.messaging.PingControlMessage instance.

pong(data='')[source]

Returns a ping control message built from a ws4py.messaging.PongControlMessage instance.

receiver()[source]

Parser that keeps trying to interpret bytes it is fed with as incoming frames part of a message.

Control message are single frames only while data messages, like text and binary, may be fragmented accross frames.

The way it works is by instanciating a wspy.framing.Frame object, then running its parser generator which yields how much bytes it requires to performs its task. The stream parser yields this value to its caller and feeds the frame parser.

When the frame parser raises StopIteration, the stream parser tries to make sense of the parsed frame. It dispatches the frame’s bytes to the most appropriate message type based on the frame’s opcode.

Overall this makes the stream parser totally agonstic to the data provider.

text_message(text)[source]

Returns a ws4py.messaging.TextMessage instance ready to be built. Convenience method so that the caller doesn’t need to import the ws4py.messaging.TextMessage class itself.

closing = None

Parsed close control messsage. Instance of ws4py.messaging.CloseControlMessage

errors = None

Detected errors while parsing. Instances of ws4py.messaging.CloseControlMessage

has_message[source]

Checks if the stream has received any message which, if fragmented, is now completed.

message = None

Parsed test or binary messages. Whenever the parser reads more bytes from a fragment message, those bytes are appended to the most recent message.

parser[source]
pings = None

Parsed ping control messages. They are instances of ws4py.messaging.PingControlMessage

pongs = None

Parsed pong control messages. They are instances of ws4py.messaging.PongControlMessage

utf8validator Module

class ws4py.utf8validator.Utf8Validator[source]

Incremental UTF-8 validator with constant memory consumption (minimal state).

Implements the algorithm “Flexible and Economical UTF-8 Decoder” by Bjoern Hoehrmann (http://bjoern.hoehrmann.de/utf-8/decoder/dfa/).

decode(b)[source]

Eat one UTF-8 octet, and validate on the fly.

Returns UTF8_ACCEPT when enough octets have been consumed, in which case self.codepoint contains the decoded Unicode code point.

Returns UTF8_REJECT when invalid UTF-8 was encountered.

Returns some other positive integer when more octets need to be eaten.

reset()[source]

Reset validator to start new incremental UTF-8 decode/validation.

validate(ba)[source]

Incrementally validate a chunk of bytes provided as bytearray.

Will return a quad (valid?, endsOnCodePoint?, currentIndex, totalIndex).

As soon as an octet is encountered which renders the octet sequence invalid, a quad with valid? == False is returned. currentIndex returns the index within the currently consumed chunk, and totalIndex the index within the total consumed sequence that was the point of bail out. When valid? == True, currentIndex will be len(ba) and totalIndex the total amount of consumed bytes.

UTF8VALIDATOR_DFA = [0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
UTF8_ACCEPT = 0
UTF8_REJECT = 1

websocket Module

class ws4py.websocket.WebSocket(sock, protocols=None, extensions=None, environ=None)[source]

Bases: object

The sock is an opened connection resulting from the websocket handshake.

If protocols is provided, it is a list of protocols negotiated during the handshake as is extensions.

If environ is provided, it is a copy of the WSGI environ dictionnary from the underlying WSGI server.

close(code=1000, reason='')[source]

Call this method to initiate the websocket connection closing by sending a close frame to the connected peer. The code is the status code representing the termination’s reason.

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.

See also

Defined Status Codes http://tools.ietf.org/html/rfc6455#section-7.4.1

close_connection()[source]

Shutdowns then closes the underlying connection.

closed(code, reason=None)[source]

Called when the websocket stream and connection are finally closed. The provided code is status set by the other point and reason is a human readable message.

See also

Defined Status Codes http://tools.ietf.org/html/rfc6455#section-7.4.1

opened()[source]

Called by the server when the upgrade handshake has succeeeded.

ponged(pong)[source]

Pong message, as a messaging.PongControlMessage instance, received on the stream.

process(bytes)[source]

Takes some bytes and process them through the internal stream’s parser. If a message of any kind is found, performs one of these actions:

  • A closing message will initiate the closing handshake
  • Errors will initiate a closing handshake
  • A message will be passed to the received_message method
  • Pings will see pongs be sent automatically
  • Pongs will be passed to the ponged method

The process should be terminated when this method returns False.

received_message(message)[source]

Called whenever a complete message, binary or text, is received and ready for application’s processing.

The passed message is an instance of messaging.TextMessage or messaging.BinaryMessage.

Note

You should override this method in your subclass.

run()[source]

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 message and finally close the connection
  • We respond to pings with pong messages.
  • Whenever an error is raised by the stream parsing, we initiate the closing of the connection with the appropiate error code.

This method is blocking and should likely be run in a thread.

send(payload, binary=False)[source]

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.

If binary is set, handles the payload as a binary message.

client_terminated = None

Indicates if the client has been marked as terminated.

environ = None

WSGI environ dictionary.

extensions = None

List of extensions supported by this endpoint. Unused for now.

protocols = None

List of protocols supported by this endpoint. Unused for now.

reading_buffer_size = None

Current connection reading buffer size.

server_terminated = None

Indicates if the server has been marked as terminated.

sock = None

Underlying connection.

stream = None

Underlying websocket stream that performs the websocket parsing to high level objects. By default this stream never masks its messages. Clients using this class should set the stream.always_mask fields to True and stream.expect_masking fields to False.

terminated[source]

Returns True if both the client and server have been marked as terminated.

class ws4py.websocket.EchoWebSocket(sock, protocols=None, extensions=None, environ=None)[source]

Bases: ws4py.websocket.WebSocket

The sock is an opened connection resulting from the websocket handshake.

If protocols is provided, it is a list of protocols negotiated during the handshake as is extensions.

If environ is provided, it is a copy of the WSGI environ dictionnary from the underlying WSGI server.

received_message(message)[source]

Automatically sends back the provided message to its originating endpoint.

Table Of Contents

Previous topic

Server

Next topic

client Package

This Page