This time, I will create a chat using Tornado, a web server and web framework made by Python. The reason for using Tornado is that it supports WebSocket by default, so it is easy to create real-time services.
The following two are used.
Use Tornado on the server side and jquery.ui.chatbox on the client side. Chatting is relatively easy with jquery.ui.chatbox.
The following code is the main processing on the server side. It records the messages sent with the people connecting to the waiters and messages.
class ChatHandler(tornado.websocket.WebSocketHandler):
waiters = set()
logs = []
def open(self, *args, **kwargs):
self.waiters.add(self)
self.write_message({'logs': self.logs})
def on_message(self, message):
message = json.loads(message)
self.logs.append(message)
for waiter in self.waiters:
if waiter == self:
continue
waiter.write_message({'img_path': message['img_path'], 'message': message['message']})
def on_close(self):
self.waiters.remove(self)
The ** open ** method registers the person who has connected and sends the log so far to that person.
The ** on_message ** method broadcasts the message sent when the message was sent to participants other than yourself. Also, add the message sent at this time to the log.
The ** on_close ** method removes the connecter from the waiters when the connection is lost. This prevents the message from being broadcast to the disconnected person.
The following is the finished product. I made it in about an hour, but it works fine. The feature is that you can open and close the chat screen by clicking the bar at the top.
Click the link below for sample code.
This time I made a chat app using Tornado. If you want to create a little real-time application in Python, you should use Tornado.
Recommended Posts