Websocket
base class for websocket operations
wsgi.websocket
in WSGI environment dictionary
In app this is the client
...
def on_message(message, client):
# client is a websocket object
...
In Middleware, Framework, Handler this is the wsgi.websocket
in environment
...
@app.route("/")
def handle_websocket(environ, start_response):
wsock = environ.get("wsgi.websocket")
...
...
@bottle.route("/")
def handle_websocket():
wsock = request.environ.get("wsgi.websocket")
...
Class variables
origin
- HTTPOrigin
headerprotocol
- supported websocket sub protocolversion
- websocket version(1, 8 or 7)path
- required path by client(eg:-if websocket url which client opened isws://localhost/hello/world?user=Ksengine&pass=1234
, path is/hello/world
)logger
= default logger(Python Docs)do_compress
- is compressed messages required by client
Class methods
handle_close
- handle close messages from client. WSocket automatically handles this.handle_ping
- handle ping(keep alive) messages from client. WSocket automatically handles this.handle_pong
- handle pong messages from client.receive
- receive one messages from client. handlesclose
,ping
,pong
messages. returnstext messages - utf-8 strings
binary messages - bytes
raises
WebSocketError
if client closed. ReturnsNone
on any error likeUnicodeError
ProtocolError
orsocket
error.
send
- Send a frame over the websocket with message as its payload. This method has following arguments.message
- binary(asbytes
) or text(as unicodestr
) message.binary
- make this argumentTrue
, if message isbytes
.do_compress
- Default value isTrue
. setFalse
to send not compressed message. To send compressed messages client should support it.close
- Close the websocket and connection, sending the specified code and message. The underlying socket object is not closed, that is the responsibility of the initiator.This method has two arguments.code
- Should be a valid websocket close code. Default is1000
.message
- reson for closing websocket connection asstr
.
Change methods
create websocket class inherited child class. for Framework and App only
...
from wsocket import Websocket, ProtocolError
import struct
class new_class(Websocket):
def handle_close(self, payload):
if not payload:
self.close(1000, "")
return
if len(payload) < 2:
raise ProtocolError("Invalid close frame: %s" % payload)
code = struct.unpack("!H", payload[:2])[0]
payload = payload[2:]
if payload:
payload.decode("utf-8")
if not self._is_valid_close_code(code):
raise ProtocolError("Invalid close code %s" % code)
self.close(code, payload)
def handle_ping(self, payload):
self.send_frame(payload, self.OPCODE_PONG)
def handle_pong(self, payload):
pass
WSocketApp.websocket_class = new_class
...
Last updated
Was this helpful?