Basic Chatting
It looks like a chat application and it allows multiple users to log in, but it has one fatal flaw: users cannot actually send or receive any chat messages. To allow users to send messages, we need to make a couple of changes. The server-side Python code has almost everything needed to support this feature; now it just needs to accept the messages from the web client and funnel them to the other users. Luckily, much of that code is already written.
Chatting on the Server Side
The Python code already has the ability to send generic messages
to users via the send_notification
method. So the
only thing we need to handle basic chatting is to catch messages from
the user and funnel them through that method. To do that, we need to add
one more URL handler to the array. In the
Application.__init__
method of
chat-server.py, make the following
addition:
class Application(tornado.web.Application):
def __init__(self):
# setup the URL handlers
handlers = [
(r"/", MainHandler),
(r"/login/?", LoginHandler),
(r"/updates/?", UpdateHandler),
(r"/send/?", SendHandler),
]
This code just sets up another URL handler so that Tornado knows
which class should respond to requests to the /send
URL. That class, SendHandler
, will be responsible for
accepting the user input, building a message, and sending it to the
receiving user. In chat-server.py, add the
following code above the Application
class:
class SendHandler(BaseHandler): def post(self): # who is the message to and from? to_user_id = self.get_argument('to_user_id') ...
Get Building the Realtime User Experience now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.