WebSocket Build a chat program

Source: Internet
Author: User

The previous article used the Ajax long polling implementation of a simple chat program, for Web real-time communication, today to try a websocket-based long connection method.

WebSocket Introduction

In order to enhance the function of web communication, WebSocket is provided in HTML5, which is not only a way of web communication, but also an application layer protocol.

WebSocket provides client-to-server and server-to-service cross-domain communication between clients and servers through the establishment of a websocket connection between the client and the service (which is actually a TCP connection, as seen later), which enables client-to-client data delivery at the same time.

Ajax Long polling is a way for clients to pull data from the server, while WebSocket can actually implement the server to push the data to the client actively. The image shows how the WebSocket works.

For WebSocket This new application layer protocol, in the implementation of the application, the client and the server will need to follow the WebSocket protocol, for more websocket content, please refer to websocket.org.

Realize

First, let's look at the code and effects of the chat program implemented through WebSocket, and then look at what WebSocket works.

Client

Since not all versions of the browser can support WebSocket, the following code is shown in the example to detect if the current browser supports WebSocket.

if (window. WebSocket) {    //supportWebSocket, + codehere}else{    alert ( "WebSocket is not supported");}

For the client, it is primarily the Updater object, which creates and maintains a WebSocket object that can interact with the server (to collect or send messages) through this WebSocket object.

varUpdater ={socket:NULL, start:function() {         varurl = "ws://" + location.host + "/chatsocket"; Updater.socket=NewWebSocket (URL); Updater.socket.onopen=function(event) {} Updater.socket.onclose=function(Event) {alert ("Server socket closed"); } updater.socket.onmessage=function(event) {updater.showmessage (event.data); }}, ShowMessage:function(message) {console.log (message); $("#inbox"). append (message); $("#message"). Val (""); } };
Service side

For the service side, this time use gevent-websocket this library, can be very convenient to install through PIP.

The server manages all messages and all WebSocket clients by messagebuffer this class. Since WebSocket is a long-connected way, it is easy to count the number of clients currently online.

classMessagebuffer (object):def __init__(self, cache_size = 200): Self.cache=[] self.cache_size=cache_size self.clients= []            defnew_message (Self, msg): Self.cache.append (msg)ifLen (Self.cache) >Self.cache_size:self.cache= self.cache[-self.cache_size:]defupdate_clients (Self, msg): forClientinchself.clients:client.send (msg)

After using WebSocket, the server code is more concise than the last time. When the client initiates a "/chatsocket" request, the server establishes a connection with the client and joins the client to the "messagebuffer.clients" list, and when the client disconnects, the client is removed from the "messagebuffer.clients" Removed from the list.

When the server receives a new message, it pushes the new message to all clients through the "messagebuffer.update_clients" method.

defapplication (env, start_response):#visit the main page    ifenv['Path_info'] =='/':        #some code to load main Page here        elifenv['Path_info'] =='/chatsocket': WS= env["Wsgi.websocket"] MessageBuffer.clients.append (WS)Print "New client Join, total client count%d"%Len (messagebuffer.clients) whileTrue:message=ws.receive ()ifMessage isNone:messageBuffer.clients.remove (WS)Print "client leave, total client count%d"%Len (messagebuffer.clients) Break            Print "Got message:%s"%Message Message="<div>{0}</div>". Format (message) messagebuffer.new_message (message) messagebuffer.update_clients ( message)
Run effect

Here's how the code works.

Since WebSocket is a long-connected way, it is convenient to count the current number of online clients.

When the server is shut down, the client can also detect the disconnection of the connection.

WebSocket working mechanism

Here's a look at how websocket is providing long-connected services to your application from a working mechanism.

WebSocket Connection Setup

Although WebSocket is a new application-layer protocol, its work is also dependent on the HTTP protocol.

With Wireshark, we can catch the following packet.

These two packets are the handshake process that establishes the WebSocket connection (WebSocket Protocol handshake):

1. The client's WebSocket instance binds to a server address that needs to be connected, and when the client connects to the service side, it sends a HTTP GET request similar to the following

In the above request there is a upgrade header, which tells the server that the communication protocol needs to be switched to WebSocket

2. Upon receipt of a request with the "Upgrade:websocket" header, if the server supports the WebSocket protocol, it switches its communication protocol to WebSocket and sends a response message header similar to the following for the client.

The status code of the response message is 101, which means agreeing to the client protocol conversion request and converting it to the WebSocket protocol. To this end, the client and server WebSocket connection is established successfully, the subsequent communication is based on the WebSocket connection.

WebSocket Connection KeepAlive

WebSocket the bottom of the work/implementation are based on the TCP protocol, so the keepalive mechanism of the connection is the same as TCP, is through the "TCP Keep-alive" heartbeat packet to ensure that the connection is always in a valid state.

WebSocket Connection off

For the shutdown of the WebSocket connection, the active shutdown is also sent "FIN, ACK" packets to complete the shutdown.

Summarize

This paper briefly introduces the WebSocket protocol in HTML5, and realizes a simple chat program through WebSocket.

WebSocket can establish a long connection between the client and the server, and provide full-duplex data transfer, which provides the mode of push-to-send.

In contrast to the Ajax long polling approach, the way the server actively pushes data is more suitable for real-time data interaction applications.

Ps:

The source code for the example can be downloaded here.

WebSocket Build a chat program

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.