Principles and use of websocket

What is websocket

WebSocket performed on a single TCP connection a full-duplex protocol communication. WebSocket enables exchange of data between the client and the server easier, allowing the server actively push data to the client. In the WebSocket API, the browser and the server only needs to complete a handshake, you can directly create a persistent connection between the two, and two-way data transmission.

Websocket protocol is a persistent, with respect to such non-persistent HTTP is the protocol.

for example:

HTTP lifecycle defined by Request, which is sending a Request, receive a Response, then HTTP1.0 in the HTTP request is over

HTTP1.1 the improvement in such a keep-alive, that is, in a HTTP connection may be sent a plurality of Request, receiving a plurality Response. But remember Request = Response, in HTTP will always be so, that a request can be only one response. And the response is passive, it can not initiate.

For websocket, the links established during the handshake on the basis of HTTP, the server can take the initiative to send data to the client.

Why use websocket

Now, many sites in order to achieve the data updates on the page, all by ajax technology polling pulls data to the server. Polling at certain time intervals (e.g., every 1 second), issues an HTTP request to the server by the browser, and returns the latest data from the server to the client browser. This traditional model brings obvious disadvantage that the browser requires constant request to the server, however, HTTP requests may contain a long head, which truly effective data may only be a small part, obviously this will waste a lot of bandwidth resources.

The relatively new technology to do the polling results are Comet ). Comet polling technology can be divided into long and streaming. Improved long polling polling technique described above, reducing the unnecessary request. It will set the expiration time some of the data, when the data has expired before sending the request to the server; the data for such a mechanism is not particularly frequent changes of circumstances. Streaming usually refers the client to use a hidden window and server to establish an HTTP long connection, the server will continue to update the connection status to maintain HTTP long connection alive; this is the case, the server can, through this long connection active data sent to the client; concurrent streaming technology in a large environment, you may test the performance of the server. Both technologies are based on the request - answer mode, not regarded as real-time technology in the true sense; every time they request, response, wasted some traffic on the same header information, and development complexity is also large .

In this case, HTML5 WebSocket protocol is defined, better able to save server resources and bandwidth, and can be more real-time communication.

Websocket use ws wss or uniform resource identifier, similar to HTTPS, which represents Websocket wss over the TLS. Such as:

ws://example.com/wsapi
wss://secure.example.com/

Websocket use the same TCP and HTTP port, you can bypass most firewalls limit. By default, Websocket protocol uses port 80; run at over TLS, 443 using the default port.

WebSocket is currently standardized by the W3C. WebSocket has been supported by Firefox 4, Chrome, Opera 10.70 and Safari 5 and other browsers.

A typical handshake request of websocket

  • Client requests:
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
Sec-WebSocket-Key: sN9cRrP/n9NdMgdcy2VJFQ==
Sec-WebSocket-Version: 13
  • Server response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec -WebSocket the Accept-: fFBooB7FAkLlXgRSz0BT3v4hq5s = 
sec -WebSocket the Location-: WS: // example.com/ 
Field Description

Field Description

  • Connection must be set to Upgrade, means that the client wishes to connect to upgrade.
  • Upgrade field must be set Websocket, expressed the wish to upgrade to Websocket agreement.
  • Sec-WebSocket-Key is a random string, the server will use these data to construct a message digest of SHA-1. The "Sec-WebSocket-Key" plus a special string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", and SHA-1 digest is calculated, followed by BASE-64 encoding the result as "Sec-WebSocket-Accept "header value is returned to the client. Doing so, it is possible to avoid mistaken for normal HTTP request is Websocket protocol.
  • Sec-WebSocket-Version of support Websocket version. RFC6455 requires version 13, version of the draft before shall abandoned.
  • Origin field is optional, typically used to represent initiate this page Websocket connection resides in the browser, similar to the Referer. However, the difference is Referer, Origin contains only the protocol and host name.
  • Other fields defined in the HTTP protocol, such as Cookie, etc., can also be used in Websocket.

How to use websocket

Websocket on how to use technology in a variety of ways Python back end, you can refer to the article "python several ways of using websocket" https://jingniao.github.io/2016/04/10/python-websocket/

Our projects are using the Django framework, this time I practice dwebsocket unfold around Django's major record websocket plug.

Installation dwesocket

Man of few words said, pip Dafa.

pip install dwesocket

use

If you want to view a view can handle both HTTP requests, the request may be processed websocket, just to view this is a decorative function  @accept_websocket package can. May also be used  @require_websocket decorator, so websocket This view allows only accepts the request, a normal HTTP request will be rejected.

If you want to provide support for all websocket request url in your application, you can use the middleware. Only need to dwebsocket.middleware.websocketmiddleware set the add to  MIDDLEWARE_CLASSES the. (If you do not need to define themselves, will not define an error, this is a bit awkward, for this optimization, I have a master Kuti Pull Request , authors still maintain hope ....)

MIDDLEWARE_CLASSES = ['dwebsocket.middleware.WebSocketMiddleware']

If each individual view allows websocket request acceptance, the settings provided  WEBSOCKET_ACCEPT_ALL for the  True.

WEBSOCKET_ACCEPT_ALL = True

Interface and property

  1. request.is_websocket()

    If the request is websocket returns True, if an ordinary http request returns False, they can be distinguished by this method.

  2. request.websocket

    After a request to establish websocket, this request will have a websocket property that the client provides a simple api communications, if request.is_websocket () is False, this property will be None.

  3. WebSocket.wait()

    Returns a message sent from a client, he will not return any value before the client closes the connection, in this case, the method returns None

  4. WebSocket.read()

    If you do not receives a new message from a client, read method returns a new message, if not, will not return. This is a non-blocking alternative method wait

  5. WebSocket.count_messages()

    Returns the number of the message queue

  6. WebSocket.has_messages()

    If you have a new message returns True, otherwise False

  7. WebSocket.send(message)

    Send a message to the client

  8. WebSocket.iter()

    websocket iterator

Practice routines

Receiving a message from the client, it sends the message back to the client and close the connection (through the view back):

from dwebsocket import require_websocket

@require_websocket
def echo(request):
    message = request.websocket.wait()
    request.websocket.send(message)

We can also make the server does not automatically close the connection, the following routine, the server will send the client to send a message back to lowercase, and increase the general response of HTTP requests, do the same operation returns:

from django.http import HttpResponse
from dwebsocket import accept_websocket

def modify_message(message):
    return message.lower()

@accept_websocket
def lower_case(request):
    IF not request.is_websocket (): # normal HTTP request
        message = request.GET['message']
        message = modify_message(message)
        return HttpResponse(message)
    else: # websocket请求
        for message in request.websocket:
            message = modify_message(message)
            request.websocket.send(message)

Change dwebsocket backend

Dwebsocket currently supports two back-end, respectively, default and uwsgi.

Default default support for Django development server itself, eventlent, gevent, and gunicore.

If you want to use uwsgi backend, add WEBSOCKET_FACTORY_CLASS in settings.py file:

WEBSOCKET_FACTORY_CLASS = 'dwebsocket.backends.uwsgi.factory.uWsgiWebSocketFactory'

Run uwsgi:

uwsgi --http :8080 --http-websockets --processes 1 \
--wsgi-file wsgi.py--async 30 --ugreen --http-timeout 300

websocket advantages and disadvantages

advantage

  • Header information exchanged between the client and the server is very small, only about 2 to 10 bytes (packet length and related);

  • The client and server can take the initiative to transmit data to each other;

  • Do not create a TCP request frequency and the destruction of the request, reducing network bandwidth resources, while saving server resources;

  • More real-time. Since the protocol is full duplex, so the server can take the initiative to send data to the client at any time. With respect to the need to wait for HTTP requests initiated by the client requests the server to respond, delayed significantly less;

  • Better binary support. Websocket defined binary frame, relative HTTP, can more easily handle binary content;

  • You can support the expansion. Websocket define an extended, the user can extend the protocol to implement a custom sub-protocol section. As part of the browser supports compression and so on.

Shortcoming

The following almost the insight, the advantages tasteless disadvantage is that the developer should not high technical requirements disadvantage, there is always a new technical process popularity.

Front-end developers:

  • Tend to have the ability to use data-driven javascript, and the need to sustain ws connection (otherwise the message can not push)

For the back-end developers:

  • First, the long connection code needs to back-end processing business is more stable (Do not put processes and frameworks crash off)

  • Two push message is relatively complex

  • Thirdly, it is under a lot of mature http ecological components can be reused, websocket relatively new

Reference material

Guess you like

Origin www.cnblogs.com/miaoweiye/p/12509868.html