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.
Client requests Web page from server side
The server responds accordingly
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.
The client requests the Web page from the server side using normal HTTP methods
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
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.
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
SSE
The 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.
SSE
Way 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.
Redis
the 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/shiyanlou
under 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