Simple online chat room based on Server-sent event

Source: Internet
Author: User
Tags live chat install redis redis server

One, the Web Instant Communication

The so-called Web instant communication, that is, we can use a mechanism on the Web page immediately notify the user of the occurrence of a thing, is not required to refresh the user page. There are many uses for Web instant messaging, such as live chat, instant push, and so on. If someone answers our questions when we visit our website, we will immediately remind us of the current e-commerce online customer service function. These features that greatly enhance the user experience are based on Web Instant messaging.

    • Normal HTTP Process

    1. Client requests Web page from server side

    2. The server responds accordingly

    3. The server returns the corresponding to the client

because the HTTP request is stateless, that is, after each request is completed, the HTTP link is disconnected, the server and browser are completely unknown to each other, only the next time to initiate a request to update the corresponding information. When it comes to this, it's easy to think that we can simply let the browser launch a request every other cycle, so that we can simulate the real-time effect to some extent, which is rotation , the term Polling.

    • Polling Process

    1. The client requests the Web page from the server side using normal HTTP methods

    2. The client executes the JavaScript polling script in the Web page, periodically sending requests to the server (such as sending a request every 5 seconds) to obtain information

    3. The server responds to each request and returns the appropriate information, just like a normal HTTP request

by rotation Way we can Get information in a relatively instant. However, because rotation's principle is to make the browser frequently requests to the server, this will to some extent lead to performance efficiency issues. One way to optimize these performance problems is to think about it. That is, when the server receives the request, it does not understand the return, but only when there is data change (or timeout). In this way, we can make use of one request maximum possible to maintain the validity of the connection, greatly reduced the polling long-polling

sse websocket sse The full name is server Send Event

if sse is not enough to meet our needs, we can use the websocket websocket TCP socket same.

    • sse Span style= "font-size:16px;font-family: ' The song Body '; > and websocket

      • is a full-duplex channel that can communicate in two directions and is more powerful; SSE is a one-way channel and can only be sent to the browser by the server.

      • websocket sse

here we have a basic understanding of some of the prior web real-time communication mechanism, in the next section, we will use SSE implement a simple online chat room.

Second, based on SSEThe implementation of the online chat room

There are many ways to push messages in online chat rooms, which we use to implement in this course SSE . To facilitate the reception of messages, we use Redis the pub/sub ability to receive and send messages. Web server side We will use the Flask implementation. If you are not familiar with flask, you can also study the relevant flask courses in the lab building. (http://www.shiyanlou.com/)

1. SSEWay of working

In the previous lesson, we learned that it SSE was based on HTTP, so how does the browser know it's a server event stream? In fact, it is very simple, that is, the HTTP header is Content-Type set text/event-stream to the right. In fact SSE , it is the browser to send an HTTP request to the server, and then the server constantly one-way to the browser push "information", the format of the information is very simple, is the prefix data: plus the data sent to the content, and then to the \n\n end.

2. Redisthe subscription feature in

Redis is a popular memory database that can be used to implement services such as caching, queuing, and so on. The Publish/Subscribe power we will use in this project course Redis . Simply put, our so-called subscription function is that we can subscribe to some channels, and then we can automatically receive this information when there are new messages on those channels. This information is posted to a specific channel when the server receives a message from the browser post. Then our clients, who subscribed to these channels, automatically receive these messages, and finally we push the messages SSE to the client.

3.Implement

Through the above analysis, the whole chat room process is very clear. Let's analyze it in the form of source code comments. /home/shiyanlouunder directory, create a directory code , and then create a source file under that directoryapp.py

#  message Generator Def event_stream ():     pubsub = r.pubsub ()      #  subscribe to ' chat ' channel     pubsub.subscribe (' chat ')     #  start listening messages, If there is a message generated in the return message     for message in pubsub.listen ():         print message        # server-send  event data format with ' data: ' Start         yield ' data: %s\n\n '  %  message[' data ']  #  login function, first access required login @app.route ('/login ',  methods=[' GET ',  ' POST ') Def login ():    if flask.request.method ==  ' POST ':         #  Log user information to session          flask.session[' user '] =flask.request.form[' user ']         Returnflask.redirect ('/') &NBSP;&NBSP;&NBSP;&NBSp;return ' <form action= ""  method= "POST" >user: <inputname= "user" > "  #   Receive javascriptpost over the message @app.route ('/post ',  methods=[' post ']) Def post ():     message = flask.request.form[' message ']    user = flask.session.get (' User ',  ' anonymous ')     now =datetime.datetime.now (). replace (microsecond=0). Time (     #  post messages to the ' chat ' channel     r.publish (' Chat ',  u ' [%s] %s:  %s '  %  (Now.isoformat (),  user, message)) Return flask. Response (status=204)


For detailed code, please log into the lab building Http://www.shiyanlou.com/courses/?course_type=project&tag=all

4.Run

Because Redis is used, the Redis server needs to be installed, and the Redis server, as well as the dependent dependencies, can be installed in the following steps.

$ sudo apt-get update
$ sudo apt-getinstall redis-server
$ sudo service Redis start
$ sudo pip install Redis
$ sudo pip install flask

After the installation is complete, run, and then see the effect through the browser access http://127.0.0.1:8989 . 650) this.width=650; "src=" http// Anything-about-doc.qiniudn.com/web_realtime/sse-chat.gif "/>

There are other project classes in detail and content welcome Landing laboratory Building Http://www.shiyanlou.com/courses/?course_type=project&tag=all

Official website: Laboratory Building http://www.shiyanlou.com

This article is from the "Lab Building" blog, please be sure to keep this source http://shiyanloucs.blog.51cto.com/9731842/1590738

Simple online chat room based on Server-sent event

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.