You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.9 KiB

import os
import tornado.ioloop
from tornado.options import define, options, parse_command_line
import tornado.web
import socketio
define("port", default=8888, help="run on the given port", type=int)
define("debug", default=False, help="run in debug mode")
sio = socketio.AsyncServer(async_mode='tornado')
async def background_task():
"""Example of how to send server generated events to clients."""
count = 0
while True:
await sio.sleep(10)
count += 1
await sio.emit('my response', {'data': 'Server generated event'},
namespace='/test')
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("app.html")
@sio.on('my event', namespace='/test')
async def test_message(sid, message):
await sio.emit('my response', {'data': message['data']}, room=sid,
namespace='/test')
@sio.on('my broadcast event', namespace='/test')
async def test_broadcast_message(sid, message):
await sio.emit('my response', {'data': message['data']}, namespace='/test')
@sio.on('join', namespace='/test')
async def join(sid, message):
sio.enter_room(sid, message['room'], namespace='/test')
await sio.emit('my response', {'data': 'Entered room: ' + message['room']},
room=sid, namespace='/test')
@sio.on('leave', namespace='/test')
async def leave(sid, message):
sio.leave_room(sid, message['room'], namespace='/test')
await sio.emit('my response', {'data': 'Left room: ' + message['room']},
room=sid, namespace='/test')
@sio.on('close room', namespace='/test')
async def close(sid, message):
await sio.emit('my response',
{'data': 'Room ' + message['room'] + ' is closing.'},
room=message['room'], namespace='/test')
await sio.close_room(message['room'], namespace='/test')
@sio.on('my room event', namespace='/test')
async def send_room_message(sid, message):
await sio.emit('my response', {'data': message['data']},
room=message['room'], namespace='/test')
@sio.on('disconnect request', namespace='/test')
async def disconnect_request(sid):
await sio.disconnect(sid, namespace='/test')
@sio.on('connect', namespace='/test')
async def test_connect(sid, environ):
await sio.emit('my response', {'data': 'Connected', 'count': 0}, room=sid,
namespace='/test')
@sio.on('disconnect', namespace='/test')
def test_disconnect(sid):
print('Client disconnected')
def main():
parse_command_line()
app = tornado.web.Application(
[
(r"/", MainHandler),
(r"/socket.io/", socketio.get_tornado_handler(sio)),
],
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=options.debug,
)
app.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()