当前位置:网站首页>Websocket for im instant messaging development: concept, principle and common sense of mistakes
Websocket for im instant messaging development: concept, principle and common sense of mistakes
2022-06-28 22:28:00 【wecloud1314】
WebSocket Birth background
In the early , Many websites are trying to implement push technology , The technology used is polling ( Also called short polling ). Polling means that the browser sends out to the server at regular intervals HTTP request , Then the server returns the latest data to the client .

This traditional model brings obvious disadvantages , That is, the browser needs to keep making requests to the server , However HTTP Requests and responses may contain long headers , The amount of data that actually works is probably only a tiny fraction of that , So this will consume a lot of bandwidth resources .
The newer polling technology is Comet. Although this technology can realize two-way communication , But you still need to make repeated requests . And in Comet The most commonly used HTTP Long connections also consume server resources .
under these circumstances ,HTML5 Defined WebSocket agreement , Can better save server resources and bandwidth , And they can communicate in real time .
Websocket Use ws or wss The unified resource identifier for (URI), among wss Indicates that TLS Of Websocket.
Such as :
ws://echo.websocket.org
wss://echo.websocket.org
WebSocket And HTTP and HTTPS Use the same TCP port , You can bypass most firewalls .
By default :
1)WebSocket Agreement to use 80 port ;
2) If running in TLS When above , By default 443 port .
WebSocket brief introduction
WebSocket It's a network transport protocol , Can be in a single TCP Full duplex communication on the connection , be located OSI The application layer of the model .WebSocket The agreement 2011 Year by year IETF Standardize to RFC 6455, After by RFC 7936 Supplementary specifications .
WebSocket Makes it easier to exchange data between client and server , Allows the server to actively push data to the client . stay WebSocket API in , The browser and the server only need to complete a handshake , A persistent connection can be created between the two , And two-way data transmission .
After introducing polling and WebSocket After that , Next, take a look at a picture XHR Polling( Short polling ) And WebSocket The difference between .
WebSocket advantage
It is generally believed that ,WebSocket The advantages are as follows :
1) Less control overhead : After the connection is created , When data is exchanged between server and client , The packet header used for protocol control is relatively small ;
2) More real time : Because the protocol is full duplex , So the server can send data to the client at any time . be relative to HTTP The request needs to wait for the client to send the request to the server to respond , Delays are significantly less ;
3) Keep connected : And HTTP The difference is ,WebSocket You need to create a connection first , This makes it a stateful protocol , After that, some state information can be omitted during communication ;
4) Better binary support :WebSocket Defined binary frame , relative HTTP, Binary content can be handled more easily ;
5) Can support extension :WebSocket Defined extensions , The user can extend the protocol 、 Implement some custom sub protocols .
because WebSocket Have the above advantages , So it is widely used in instant messaging /IM、 Real time audio and video 、 Online education and games .
For front-end developers , Want to use WebSocket Powerful capabilities provided , You must master WebSocket API, Let's take you to know WebSocket API.
At present, the mainstream Web Browsers support WebSocket, So we can use it safely in most projects .
In the browser to use WebSocket Capabilities provided , We must first create WebSocket object , This object provides for creating and managing WebSocket Connect , And can send and receive data through the connection API.
Use WebSocket Constructors , We can easily construct a WebSocket object .
Next, we will introduce... From the following four aspects WebSocket API:
1)WebSocket Constructors ;
2)WebSocket Object properties ;
3)WebSocket Methods ;
4)WebSocket event .
So let's start with WebSocket Start with the constructor of .
Constructors
WebSocket The syntax of the constructor is :
const myWebSocket = newWebSocket(url [, protocols]);
The relevant parameters are as follows :
1)url: Represents a connected URL, This is a WebSocket The server will respond to URL;
2)protocols( Optional ): A protocol string or an array containing protocol strings .
For 2) spot : These strings are used to specify the sub protocol , In this way, a single server can implement multiple WebSocket Sub protocol .
such as : You may want a server to be able to work according to a specified protocol (protocol) Dealing with different types of interaction . If you do not specify a protocol string , Is assumed to be an empty string . Instant messaging development

Use WebSocket Constructor , When the port trying to connect is blocked , Will throw out SECURITY_ERR abnormal .
The specific meaning of each attribute is as follows :
1)binaryType: Connect using binary data types ;
2)bufferedAmount( read-only ): Number of bytes not sent to the server ;
3)extensions( read-only ): Server selected extensions ;
4)onclose: Used to specify the callback function after the connection is closed ;
5)onerror: Used to specify callback function after connection failure ;
6)onmessage: Used to specify the callback function when receiving information from the server ;
7)onopen: Used to specify a callback function after a successful connection ;
8)protocol( read-only ): Used to return the name of the sub protocol selected by the server ;
9)readyState( read-only ): Returns the current WebSocket Connection state of , share 4 States :
- CONNECTING — Connecting , The corresponding value is 0;
- OPEN — Connected and able to communicate , The corresponding value is 1;
- CLOSING — The connection is closing , The corresponding value is 2;
- CLOSED — The connection was closed or did not succeed , The corresponding value is 3
10)url( read-only ): The return value is when the constructor creates WebSocket When an instance object URL The absolute path of .
WebSocket There are two main methods :
1)close([code[, reason]]): This method is used to turn off WebSocket Connect , If the connection is closed , This method does nothing ;
2)send(data): This method will need to pass WebSocket The data that links to the server is queued , And increase according to the size of the data to be transmitted bufferedAmount Value . If the data cannot be transmitted ( For example, the data needs to be cached and the buffer is full ) when , The socket will close itself .
event
Use addEventListener() Or assign an event listener to WebSocket Object's oneventname attribute , To monitor the following events .
Here are a few events :
1)close: When one WebSocket Triggered when the connection is closed , It can also be done through onclose Property to set ;
2)error: When one WebSocket Triggered when the connection is closed due to an error , It can also be done through onerror Property to set ;
3)message: When passed WebSocket Trigger when data is received , It can also be done through onmessage Property to set ;
4)open: When one WebSocket Triggered on successful connection , It can also be done through onopen Property to set .
Introduction after WebSocket API, Let's give an example of using WebSocket An example of sending plain text .
边栏推荐
- torch. nn. Transformer import failed
- MSCI 2022年市场分类评估
- apipost脚本使用讲解一~全局变量
- 【selenium自动化过程中的api抓包】browsermobproxy的安装和配置
- Considerations on the construction of operation and maintenance system - stability
- How to make beautiful pictures
- 昨天晚上失眠
- 职业问诊 | 面试中被问到意向薪资时,该怎么回答?
- 职场人调研报告:裸辞占比最高的居然是中年人
- 2022-06-28: what does the following golang code output? A:true; B:false; C:panic; D: Compilation failed. package main import “fmt“ func main() {
猜你喜欢

Windows mysql5.7 enable binlog log

Zadig + cave Iast: let safety dissolve in continuous delivery

Rosdep update using fishros to solve ros1/ros2 problems 2022

Axure custom components

6月底了,让我康康有多少准备跳槽的

What does project management really manage?

Zadig 面向开发者的自测联调子环境技术方案详解

Zadig 面向開發者的自測聯調子環境技術方案詳解

6年心得,从功能测试到测试开发,送给在测试路上一路走到黑的你

10、标准I/O输入输出重定向及管道
随机推荐
00 後雲原生工程師:用 Zadig 為思創科技(廣州公交)研發開源節流
职场进阶 | 了解岗位优势三板斧之“进场”
C#/VB.NET 将PDF转为Excel
Zadig + cave Iast: let safety dissolve in continuous delivery
After reading the list of global patent and chip buyers, I understand that high innovation can lead to high profits
Steady! How thousands of micro services can quickly access Zadig (helm chart)
Mysql通过ibd文件恢复数据的详细步骤
torch.nn.Transformer导入失败
torch. nn. Transformer import failed
重磅!CDA认证考试备考答疑上线
With the development of industrial Internet as the starting point, the industry can enter a new stage of development
题解 洛谷P1762 偶数/6.21校内考试T2
杆会睡不着觉
Yiming Anke submitted a statement to the Hong Kong Stock Exchange: the loss doubled in 2021, and the past financing amount was exaggerated
Visual studio 2022 17.1 is now available!
Dart的类扩展、可选类型扩展
How to use the style label of jade template- How to use the style tag with jade templates?
Zadig 构建究竟何强大?一起来实践
go语言插件平台的实现思路
QtCreator5.15.0源码编译全过程记录