Last active
December 15, 2015 15:49
-
-
Save dodolboks/5284171 to your computer and use it in GitHub Desktop.
websocket like server in python with bottle + gevent-socket.io
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from gevent import monkey; monkey.patch_all() | |
from bottle import request, Bottle, abort | |
from socketio.namespace import BaseNamespace | |
from socketio.mixins import RoomsMixin, BroadcastMixin | |
from socketio import socketio_manage | |
import redis | |
import json | |
from socketio.server import SocketIOServer | |
import os, re | |
app = Bottle() | |
class ChatNamespace(BaseNamespace, RoomsMixin, BroadcastMixin): | |
def listener(self, chan): | |
#r = redis_connection().pubsub() | |
r = redis.StrictRedis() | |
r = r.pubsub() | |
r.subscribe(chan) | |
while True: | |
for m in r.listen(): | |
if m['type'] == 'message': | |
data = json.loads(m["data"]) | |
if m["channel"] == 'cmd': | |
self.emit("cmd", data) | |
else: | |
self.emit("chat", data) | |
def on_join(self, room): | |
self.room = room | |
self.join(room) | |
return True | |
def on_message(self, message): | |
print message | |
self.emit('message', message); | |
def on_subscribe(self, user): | |
# self.spawn(self.listener, 'chat') | |
self.spawn(self.listener, 'chat_user_%s' % str(user["userid"])) | |
@app.route('/socket.io/<arg:path>') | |
def socketio(*arg, **kw): | |
if request.environ.has_key('socketio'): | |
socketio_manage(request.environ, {'': ChatNamespace}, request=request) | |
return "start server" | |
if __name__ == '__main__': | |
print ('Listening on port http://127.0.0.1:6231 and on ' | |
'port 843 (flash policy server)') | |
#SocketIOServer(('127.0.0.1', 6999), app, resource="socket.io", | |
SocketIOServer(('127.0.0.1', 11400), app, resource="socket.io", | |
policy_server=False).serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment