Simple online chat room based on Server-Sent Event, server-sentevent

Source: Internet
Author: User
Tags install redis redis server

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
    1. Client Requests webpage from server
    2. The server responds accordingly.
    3. 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
    1. The client uses the common http Method to request webpages from the server.
    2. 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.
    3. 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 SSEImplementation of Online Chat rooms

There are many ways to push messages in online chat rooms. We use this courseSSE. We useRedisOfpub/subFunction 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. SSEMethod of work

In the previous course, we learned thatSSEIt 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-TypeSettext/event-streamYou can. ActuallySSEThat 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\nEnd.

2. RedisSubscription function in

Redis is a popular memory database that can be used for caching, queue, and other services. In this project course we will useRedisPublish/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 throughSSEPush 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/shiyanlouDirectory to create a directorycodeAnd 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:8989You 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

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.