How to determine whether the protocol is Websocket in Http Header

How to determine whether the protocol is Websocket in Http Header

[[398343]]

This article is reprinted from the WeChat public account "Learn Front-end in Three Minutes", author sisterAn. Please contact the WeChat public account "Learn Front-end in Three Minutes" to reprint this article.

introduction

First, to answer this question, http determines whether the current protocol needs to be upgraded to websocket by judging whether the header contains Connection: Upgrade and Upgrade: websocket. Let's take a look at the WebSocket protocol and its origin.

WebSocket Origin

Before WebSocket, if two-way communication between the client and the service is required, it needs to be implemented through HTTP polling. HTTP polling is divided into polling and long polling:

Among them, polling means that the browser starts a timer through JavaScript, and then sends requests to the server at fixed intervals to ask the server whether there is any new message. Disadvantages:

  • Not real-time enough
  • Frequent requests will put great pressure on the server

Long polling means that when a browser sends a request, the server will wait for a while and reply only when there is a message. This mechanism temporarily solves the real-time problem, but it brings new problems:

  • A server running in multi-threaded mode will cause most threads to be suspended most of the time, greatly wasting server resources.
  • If an HTTP connection has no data transmission for a long time, any gateway on the link may close the connection, but the gateway is beyond our control.

Therefore, HTML5 adds the WebSocket protocol, which can establish an unrestricted two-way communication channel between the browser and the server.

Why can WebSocket connections achieve full-duplex communication but HTTP connections cannot?

In fact, the HTTP protocol is built on the TCP protocol. The TCP protocol itself implements full-duplex communication, but the request-response mechanism of the HTTP protocol limits full-duplex communication. After the WebSocket connection is established, it is actually just a simple provision: Next, we will not use the HTTP protocol for communication, but send data directly to each other.

Advantages of WebSocket:

  • Less control overhead: After the connection is established, when the server and client exchange data, the packet header used for protocol control is relatively small
  • Stronger real-time performance: Since the protocol is full-duplex, the server can actively send data to the client at any time
  • Maintaining connection status: Unlike HTTP, WebSocket needs to establish a connection first, which makes it a stateful protocol, and some state information can be omitted during subsequent communication
  • Better binary support: WebSocket defines binary frames, which makes it easier to handle binary content than HTTP.

Supports extensions: WebSocket defines extensions, and users can extend the protocol and implement some customized sub-protocols

WebSocket Protocol

WebSocket uses a Uniform Resource Identifier (URI) of ws or wss, where wss indicates WebSocket using TLS.

ws:// data is not encrypted and is visible to any middleman.

wss:// is a WebSocket based on TLS, similar to HTTPS being HTTP based on TLS). The transport security layer encrypts the data at the sender and decrypts it at the receiver.

http determines whether it needs to be upgraded to the websocket protocol by checking whether the header contains Connection: Upgrade and Upgrade: websocket. In addition, there are other headers:

  • Sec-WebSocket-Key: A security key randomly generated by the browser
  • Sec-WebSocket-Version : WebSocket protocol version
  • Sec-WebSocket-Extensions: Used to negotiate the WebSocket extensions to be used in this connection
  • Sec-WebSocket-Protocol :Protocol

When the server agrees to the WebSocket connection, it returns a response code of 101.

Test address: https://www.websocket.org/echo.html

Once the socket is established, we should listen for events on the socket. There are 4 events in total:

  • open : The connection has been established
  • message: received data
  • error :WebSocket error
  • close : The connection is closed

If we want to send a message, we can use socket.send(data)

  1. let socket = new WebSocket( "wss://echo.websocket.org" )
  2.  
  3. socket.onopen = function (e) {
  4. console.log( "[open] Connection established" )
  5. // Send a message
  6. socket.send( "My name is an" )
  7. }
  8.  
  9. socket.onmessage = function (event) {
  10. console.log(`[message] Data received from server: ${event.data}`)
  11. }
  12.  
  13. socket.onclose = function (event) {
  14. // ...
  15. }
  16.  
  17. socket.onerror = function (error) {
  18. console.log(`[error] ${error.message}`)
  19. }

Summarize

WebSocket uses the uniform resource identifier of ws or wss. It determines whether it needs to be upgraded to the websocket protocol by judging whether the header contains Connection: Upgrade and Upgrade: websocket. In addition, it also contains headers such as Sec-WebSocket-Key and Sec-WebSocket-Version. When the server agrees to the WebSocket connection, it returns a response code of 101. Its API is very simple.

method:

  • socket.send(data)
  • socket.close([code], [reason])

event:

  • open
  • message
  • error
  • close

refer to:

WebSocket: https://www.liaoxuefeng.com/wiki/1022910821149312/1103303693824096

WebSocket: https://zh.javascript.info/websocket

You don't know WebSocket: https://juejin.cn/post/6854573221241421838

Source: https://github.com/Advanced-Frontend/Daily-Interview-Question

<<:  Graph Algorithm Series: Shortest Path in Computational Graph

>>:  If you still don’t recognize the USB interface after reading this article, come and find me!

Recommend

Code Comics | TCP three-way handshake

[[356210]] This article is reprinted from WeChat ...

A must-have for 5G engineers! A complete list of 5G protocols

The three major operators have already commercial...

HostMayo: $2.5/month-1GB/20G SSD/unlimited traffic/Los Angeles data center

I searched the blog and found that the earliest i...

Expert: It’s time to promote 5G application innovation

Wang Zhiqin, deputy director of the China Academy...

Wireless AP Capacity and Network Bandwidth Calculation Method

Wireless AP is the access point for users to ente...

5G becomes a strong driving force for edge computing

Edge computing is one of the most exciting new co...