kore

Kore is a web application platform for writing scalable, concurrent web based processes in C or Python.
Commits | Files | Refs | README | LICENSE | git clone https://git.kore.io/kore.git

commit 5485967547ddc8d6839512a5c3cceafc57d0cb76
parent 75108349687ff565e44875dcc0347764e92942ec
Author: Joris Vink <joris@coders.se>
Date:   Sun, 29 Jan 2017 22:57:55 +0100

add websocket example to python

Diffstat:
examples/python/assets/frontend.html | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
examples/python/src/websockets.py | 21+++++++++++++++++++++
2 files changed, 81 insertions(+), 0 deletions(-)

diff --git a/examples/python/assets/frontend.html b/examples/python/assets/frontend.html @@ -0,0 +1,60 @@ +<!DOCTYPE> +<html> +<head> +<script> +var socket = null; +var sent = 0; +var recv = 0; +var length = 65536; + +function open(evt) { + var msg = ""; + var alphabet = "abcdefghijklmnopqrstuvwxyz"; + + for (i = 0; i < length; i++) + msg += alphabet.charAt(Math.floor(Math.random() * alphabet.length)); + + message(msg); +} + +function message(msg) { + socket.send(msg); + sent = sent + 1; + update(); +} + +function update() { + var cnt = document.getElementById("counter"); + + cnt.innerHTML = "Recv: " + recv + " Sent: " + sent; +} + +function onmessage(evt) { + recv = recv + 1; + update(); + + message(evt.data); +} + +function connect() { + socket = new WebSocket("ws://127.0.0.1:8888/ws"); + + socket.onopen = function(evt) { open(evt) }; + socket.onclose = function(evt) { alert("closed"); }; + socket.onmessage = function(evt) { onmessage(evt) }; + socket.onerror = function(evt) { alert("onerror"); }; +} +</script> +</head> + +<body> + +<form action="/" onsubmit="connect(); return false;"> +<input type="submit" value="connect"> +</form> + +<div id="counter"> +</div> + +</body> +</html> diff --git a/examples/python/src/websockets.py b/examples/python/src/websockets.py @@ -0,0 +1,21 @@ +# using kore websockets via python. + +import kore + +def onconnect(c): + kore.log(kore.LOG_INFO, "%s: py connected" % c) + +def onmessage(c, op, data): + kore.log(kore.LOG_INFO, "%s: got message" % c) + kore.websocket_broadcast(c, op, data, kore.WEBSOCKET_BROADCAST_GLOBAL) + +def ondisconnect(c): + kore.log(kore.LOG_INFO, "%s: py disconnecting" % c) + +def ws_connect(req): + try: + req.websocket_handshake("onconnect", "onmessage", "ondisconnect") + except: + req.response(500, b'') + + return kore.RESULT_OK