Simple online chat room based on Server-Sent Event, server-sentevent
WebInstant Messaging
The so-called instant Web communication means that we can use a mechanism to immediately notify users of one thing on the webpage without refreshing the webpage. Web instant messaging is widely used, such as real-time chat and instant push. For example, if someone answers our questions when logging on to the browser, zhihu will immediately remind us, such as the online customer service function of e-commerce. These functions greatly improve user experience are implemented based on Web instant messaging.
- Common HTTP Process
- Client Requests webpage from server
- The server responds accordingly.
- The server returns the result to the client.
Because HTTP requests are stateless, that is to say, after each request is complete, the HTTP link is disconnected, and the server and the browser are completely unknown to each other, only the next request can be initiated to update the corresponding information. Speaking of this, we can easily ask the browser to initiate a request every other cycle, so that we can simulate the real-time effect to a certain extent. This is the round training, the term is Polling.
- Polling Process
- The client uses the common http Method to request webpages from the server.
- The client executes the JavaScript polling script on the webpage and periodically sends requests to the server (for example, every five seconds) to obtain information.
- The server responds to each request and returns the corresponding information, just like a normal http request.
Through round training, we can obtain information relatively instantly. However, the principle of rotation training is that the browser initiates frequent requests to the server, which may cause performance efficiency problems to some extent. To optimize these performance problems, people have come up with another method. That is, when the server receives a request, it does not understand the returned result, but returns the result only when there is a data change (or timeout. In this way, we can use the maximum possible connection validity of a request to greatly reduce the number of requests in Polling. This method is called Long round training, also called Long-Polling.
The preceding method is a common method for implementing real-time Web communication. Of course, after HTML5 is launched, we will have a better choice. In HTML5, we can use SSE or WebSocket. The full name of SSE is Server Send Event, which is easy to understand. That is, the server pushes data. Is it exciting to see it here? In fact, in many cases, we only need this simple feature: the server pushes data to the browser. Such as pushing Game Information and stock price changes.
If SSE cannot meet our needs, we can use WebSocket. When WebSocket is used, a full-duplex channel can be established between the browser and the server to send messages to each other, and the message is completely timely, just like using tcp socket.
- Simple comparison between SSE and WebSocket:
- WebSocket is a full-duplex channel that supports two-way communication and is more powerful. SSE is a one-way channel and can only be sent from the server to the browser.
- WebSocket is a new protocol that requires server support. SSE is deployed on the HTTP protocol and is supported by existing server software.
- SSE is a lightweight protocol, which is relatively simple; WebSocket is a heavier protocol, which is relatively complex.
At this point, we have learned about some pre-defined real-time Web communication mechanisms. In the next section, we will use SSE to implement a simple online chat room.
Based on
SSE
Implementation of Online Chat rooms
There are many ways to push messages in online chat rooms. We use this courseSSE
. We useRedis
Ofpub/sub
Function to receive and send messages. On the Web server, we will useFlask
. If you are not familiar with Flask, you can also take related Flask courses in the lab building. (Http://www.shiyanlou.com /)
1.
SSE
Method of work
In the previous course, we learned thatSSE
It is implemented based on HTTP. How does the browser know that this is a server event stream? In fact, it is very simple, that is, the HTTP HeaderContent-Type
Settext/event-stream
You can. ActuallySSE
That is, the browser sends an HTTP request to the server, and the server continuously pushes "information" to the browser in one way. The format of the information is also very simple, that is, the prefix.data:
Add the sent data content, and then\n\n
End.
2.
Redis
Subscription function in
Redis is a popular memory database that can be used for caching, queue, and other services. In this project course we will useRedis
Publish/subscribe functions. Simply put, we call the subscription function to subscribe to some channels, and then we can automatically receive new messages from these channels. When the server receives a POST message from the browser, it will publish the message to a specific channel. Then, the clients that have subscribed to these channels will automatically receive these messages. Finally, we will pass these messages throughSSE
Push to the client.
3. Implementation
After the above analysis, the entire chat room process has been very clear. The following is an analysis by using source code annotations. In/home/shiyanlou
Directory to create a directorycode
And then create the source file in this directory.app.py
# Message generator def event_stream (): pubsub = r. pubsub () # subscribe to the 'chat' channel pubsub. subscribe ('chat') # start to listen to messages. If a message is generated, it is returned for message in pubsub. listen (): print message # the data format of Server-Send Event starts with 'data: 'yield 'data: % s \ n \ n' % message ['data'] # log on to the function. You need to log on to @ app for the first visit. route ('/login', methods = ['get', 'post']) def login (): if flask. request. method = 'post': # record user information to the session flask. session ['user'] = flask. request. form ['user'] return flask. redirect ('/') return '<form action = "" method = "post"> user: <input name = "user"> '# receives the javascript post message @ app. route ('/Post', methods = ['post']) def post (): message = flask. request. form ['message'] user = flask. session. get ('user', 'anonus us') now = datetime. datetime. now (). replace (microsecond = 0 ). time () # publish the message to the 'chat' Channel r. publish ('chat ', U' [% s] % s: % s' % (now. isoformat (), user, message) return flask. response (status = 204)
Please log on to the lab building http://www.shiyanlou.com/courses/ for detailed code? Course_type = project & tag = all
4. Run
Because Redis is used, you need to install the redis server. you can install the redis server and related dependent packages by following these steps.
$ sudo apt-get update$ sudo apt-get install redis-server$ sudo service redis start$ sudo pip install redis$ sudo pip install flask
After the installation is complete, run and accesshttp://127.0.0.1:8989
You can see the effect.
Other project courses and detailed description of the content welcome to the http://www.shiyanlou.com/courses/ laboratory building? Course_type = project & tag = all
Official Website: Lab Building http://www.shiyanlou.com