Skip to content

Instantly share code, notes, and snippets.

@kfish
Last active March 8, 2019 23:37
Show Gist options
  • Save kfish/c4495cfe2a2e250a119057e12ea94a7f to your computer and use it in GitHub Desktop.
Save kfish/c4495cfe2a2e250a119057e12ea94a7f to your computer and use it in GitHub Desktop.
A cherrypy websockets server to broadcast, eg. for system monitoring
# To use this, you need to implement some class with a read() method, eg.
#
# class MyReader(object):
# def __init__(self, path):
# self.path = path
#
# def read(self):
# with open(self.path, 'r') as f:
# return f.read()
# ...
#
# myReader = MyReader('/etc/motd')
#
try:
import wsaccel
wsaccel.patch_ws4py()
except ImportError:
pass
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import WebSocket
import cherrypy
from cherrypy.process import plugins
BASE_URL = None
bus = cherrypy.engine
class MonitorWebSocketHandler(WebSocket):
def received_message(self, m):
self.send(bus.websockets.currentData)
class MonitorWebSocketPlugin(WebSocketPlugin):
def __init__(self, bus, reader):
WebSocketPlugin.__init__(self, bus)
self.reader = reader
self.currentData = reader.read()
plugins.Monitor(bus, self.broadcastChanges, 0.1).subscribe()
def broadcastChanges(self):
newData = self.reader.read()
if (newData != self.currentData):
bus.publish('websocket-broadcast', newData)
self.currentData = newData
myReader = ## Some object with a read() method that returns whatever you want to broadcast
cherrypy.tools.websocket = WebSocketTool()
bus.websockets = MonitorWebSocketPlugin(bus, myReader)
class Root(object):
@cherrypy.expose
def index(self):
return myReader.read()
@cherrypy.expose
@cherrypy.tools.websocket(handler_cls=MonitorWebSocketHandler)
def ws(self):
handler = cherrypy.request.ws_handler
cherrypy.log("Handler created: %s" % repr(handler))
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == '__main__':
bus.websockets.subscribe()
conf = {
'/': {
'tools.CORS.on': True,
},
'/ws': {
'tools.CORS.on': True,
'tools.websocket.on': True,
'tools.websocket.handler_cls': MonitorWebSocketHandler
}
}
cherrypy.tools.CORS = cherrypy.Tool('before_finalize', CORS)
cherrypy.server.socket_host = '0.0.0.0'
app = Root()
cherrypy.tree.mount(app, '/', config=conf)
cherrypy.config.update(conf)
bus.signals.subscribe()
bus.start()
bus.block()
@kfish
Copy link
Author

kfish commented May 11, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment