Quickly learn about websocket in ten minutes! !

What is WebSocket
Definition
Websocket is a persistent network communication protocol that can be performed on a single TCP connectionFull double Industrial communication, there is no concept of Request and Response. The status of the two is completely equal. Once the connection is established, two-way data transmission can be carried out between the client and the server in real time
Relationships and Differences
- HTTP
- ##HTTP is a non-persistent protocol. The client wants to know the processing progress of the server. It can only be done by constantly using
- Ajax
for polling or usinglong poll, but the former puts a lot of pressure on the server, and the latter will cause blocking due to waiting for Response
Although http1.1 is enabled by default - keep-alive
Long connections maintain thisTCP channelso that in an HTTP connection, you can Send multiple Requests and receive multiple Responses, but a request can only have one response. Moreover, this response is also passive and cannot be initiated actively.Although websocket is a protocol independent of HTTP, websocket must rely on the HTTP protocol for a - handshake
(the handshake phase is the same). After the handshake is successful, the data is transferred directly from TCP Channel transmission has nothing to do with HTTP. You can use a picture to understand the intersection between the two, but not all.
- ##socket
- ##socket is also called
- is different from HTTP and WebSocket. Socket is not a protocol. It is an interface encapsulation of the transport layer protocol (can be mainly understood as TCP/IP) at the program level. It can be understood as a calling interface (API) that can provide end-to-end communication. For programmers, they need to create a socket instance on the A side and provide this instance with the IP of the B side to which it wants to connect. address and port number, and create another socket instance on the B side and bind the local port number to listen. When A and B establish a connection, the two parties establish an end-to-end TCP connection, allowing two-way communication. WebSocket draws on the idea of sockets and provides a similar two-way communication mechanism between client and server
-
Application scenarios - WebSocket can do barrages, message subscriptions, multi-player games, Collaborative editing, real-time quotations of stock funds, video conferencing, online education, chat rooms and other applications can monitor server-side changes in real time
Websocket handshake request message:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
The following are the differences from traditional HTTP messages: Upgrade: websocket Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13
Sec-WebSocket-Key
is generated by Randomly generated by the browser to verify whether Websocket communication is possible to prevent malicious or unintentional connections.Sec_WebSocket-Protocol is a user-defined string used to identify the protocol required by the service
Sec-WebSocket-Version indicates support WebSocket version.
Server response:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat
- 101 Response code
- indicates that the protocol needs to be converted.
Connection: Upgrade Represents a request to upgrade a new protocol.
Upgrade: websocket means upgrading to WebSocket protocol.
Sec-WebSocket-Accept is the Sec-WebSocket-Key that has been confirmed by the server and encrypted. Used to prove that communication can occur between the client and the server.
Sec-WebSocket-Protocol indicates the final protocol used.
At this point, the client and server have successfully established a Websocket connection via handshake. HTTP has completed all its work. The next step is to communicate in full accordance with the Websocket protocol.About Websocket
WebSocket HeartbeatThere may be some unknown circumstances that cause SOCKET to be disconnected, but the client and server do not know it, and the client needs to send a # regularly. ##Heartbeat PingLet the server know that it is online, and the server must also reply with a
Heartbeat Pongto tell the client that it is available, otherwise it will be regarded as disconnected
WebSocket StatusThe readyState attribute in the WebSocket object has four states:
- 3: Indicates that the connection has been closed, or failed to open the connection
- WebSocket practice
- The server receives and sends messages
- WebSocket server part, this article will use Node.js to build
installation
expressand
wsresponsible for processing the WebSocket protocol:
npm install express ws
installation Package.json after success: Then create the server.js file in the root directory: <pre class='brush:php;toolbar:false;'>//引入express 和 ws
const express = require(&#39;express&#39;);
const SocketServer = require(&#39;ws&#39;).Server;
//指定开启的端口号
const PORT = 3000;
// 创建express,绑定监听3000端口,且设定开启后在consol中提示
const server = express().listen(PORT, () => console.log(`Listening on ${PORT}`));
// 将express交给SocketServer开启WebSocket的服务
const wss = new SocketServer({ server });
//当 WebSocket 从外部连接时执行
wss.on(&#39;connection&#39;, (ws) => {
//连接时执行此 console 提示
console.log(&#39;Client connected&#39;);
// 对message设置监听,接收从客户端发送的消息
ws.on(&#39;message&#39;, (data) => {
//data为客户端发送的消息,将消息原封不动返回回去
ws.send(data);
});
// 当WebSocket的连接关闭时执行
ws.on(&#39;close&#39;, () => {
console.log(&#39;Close connected&#39;);
});
});</pre>Execute node server.js to start the service. After the port is opened, a listening time print prompt will be executed to explain the service. Started successfully
After opening WebSocket, the server will listen in the message, receive the parameter data to capture the message sent by the client, and then use send to send the message
The client receives and sends the message
Create index.html and index.js files in the root directory respectively
- index.html
<html>
<body>
<script ></script>
</body>
</html>- index.js
// 使用WebSocket的地址向服务端开启连接
let ws = new WebSocket('ws://localhost:3000');
// 开启后的动作,指定在连接后执行的事件
ws.onopen = () => {
console.log('open connection');
};
// 接收服务端发送的消息
ws.onmessage = (event) => {
console.log(event);
};
// 指定在关闭后执行的事件
ws.onclose = () => {
console.log('close connection');
};上面的url就是本机node开启的服务地址,分别指定连接(onopen),关闭(onclose)和消息接收(onmessage)的执行事件,访问html,打印ws信息
打印了open connection说明连接成功,客户端会使用onmessage处理接收
其中event参数包含这次沟通的详细信息,从服务端回传的消息会在event的data属性中。
手动在控制台调用send发送消息,打印event回传信息:
服务端定时发送
上面是从客户端发送消息,服务端回传。我们也可以通过setInterval让服务端在固定时间发送消息给客户端:
server.js修改如下:
//当WebSocket从外部连接时执行
wss.on('connection', (ws) => {
//连接时执行此 console 提示
console.log('Client connected');
+ //固定发送最新消息给客户端
+ const sendNowTime = setInterval(() => {
+ ws.send(String(new Date()));
+ }, 1000);
- //对message设置监听,接收从客户端发送的消息
- ws.on('message', (data) => {
- //data为客户端发送的消息,将消息原封不动返回回去
- ws.send(data);
- });
//当 WebSocket的连接关闭时执行
ws.on('close', () => {
console.log('Close connected');
});
});客户端连接后就会定时接收,直至我们关闭websocket服务
多人聊天
如果多个客户端连接按照上面的方式只会返回各自发送的消息,先注释服务端定时发送,开启两个窗口模拟:
如果我们要让客户端间消息共享,也同时接收到服务端回传的消息呢?
我们可以使用clients找出当前所有连接中的客户端 ,并通过回传消息发送到每一个客户端 中:
修改server.js如下:
...
//当WebSocket从外部连接时执行
wss.on('connection', (ws) => {
//连接时执行此 console 提示
console.log('Client connected');
- //固定发送最新消息给客户端
- const sendNowTime = setInterval(() => {
- ws.send(String(new Date()));
- }, 1000);
+ //对message设置监听,接收从客户端发送的消息
+ ws.on('message', (data) => {
+ //取得所有连接中的 客户端
+ let clients = wss.clients;
+ //循环,发送消息至每个客户端
+ clients.forEach((client) => {
+ client.send(data);
+ });
+ });
//当WebSocket的连接关闭时执行
ws.on('close', () => {
console.log('Close connected');
});
});这样一来,不论在哪个客户端发送消息,服务端都能将消息回传到每个客户端 : 可以观察下连接信息:
总结
纸上得来终觉浅,绝知此事要躬行,希望大家可以把理论配合上面的实例进行消化,搭好服务端也可以直接使用测试工具好好玩耍一波
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of Quickly learn about websocket in ten minutes! !. For more information, please follow other related articles on the PHP Chinese website!
Common Vue Reactivity Pitfalls and SolutionsJul 23, 2025 am 03:54 AMCommon problems with Vue responsive systems include: 1. Directly adding object properties does not trigger updates, and attributes need to be defined in advance; 2. Array subscript assignment does not update the view, $set or mutation methods such as splice should be used; 3. After deconstructing nested objects, they do not track them, and they need to be modified through the original path; 4. Accessing the DOM without completing asynchronous update causes old values to be read, and $nextTick should be used to wait for updates. Mastering the solutions to these problems can effectively avoid responsive traps.
Understanding Frontend Build ProcessesJul 23, 2025 am 03:52 AMThe front-end construction process is a process of converting development code into an efficient browser running form, including code compilation, module packaging, resource optimization, and version control. Common processes include: 1. Code compilation such as TypeScript to JS; 2. Module packaging and merging files; 3. Compressing JS, CSS, and image optimization; 4. Automatic hash to prevent cache. Mainstream tools such as Webpack and Vite each have their own focus, and their configuration includes entry, output, loader, and plug-ins. Build a separate development and production model. The former is hot update without compression, while the latter is compressed with TreeShaking. Common problems include module path errors, package size is too large, syntax support and image processing problems. Debugging can pass error message, dist structure checking, and sourc
Vue.js Transition Components for AnimationsJul 23, 2025 am 03:39 AMThe key to implementing animations using Vue.js' Transition component is to understand its working mechanism and class name rules. Transition component is suitable for the entry, departure and update status of elements, and realizes fading or sliding effects by wrapping elements and matching CSS class names; for example, wrapping elements controlled by v-if, and defining classes such as fade-enter-active, fade-leave-active, etc. to control transition time and styles; entry animations are triggered sometimes when elements are from scratch, and exit animations are triggered when elements are about to be hidden or destroyed; for list animations, they should be used, specify keys for each element and set tag attributes to render them into target tags, and support sorting animations, through .lis
Frontend CI/CD with GitHub Actions or GitLab CIJul 23, 2025 am 03:38 AMThe choice of GitHubActions or GitLabCI depends on the platform where the code repository is located. If it is on GitHub, choose GitHubActions. If it is on GitLab, use GitLabCI. Both can realize core functions such as automatic construction, testing and deployment. 1. Platform matching: GitHub project uses GitHubActions more natural, while GitLab project uses GitLabCI more convenient, and their integration is more convenient for permission management; 2. Configuration method: Both are based on YAML, but the keywords are different, such as GitHub uses jobs and steps, and GitLab uses script; 3. Deployment process: GitHubActions has
Frontend Build Time OptimizationJul 23, 2025 am 03:37 AMThe core of optimizing front-end build time is to reduce redundant work, improve processing efficiency, utilize caches and select efficient tools. 1. Use TreeShaking and code segmentation reasonably to ensure that it is introduced on demand and dynamic import reduces the packaging volume; 2. Reduce unnecessary loader processing, exclude node_modules, upgrade loaders and relax the scope of Babel translation; 3. Use the caching mechanism to speed up repeated construction, enable Webpack cache, CI cache and use offline installation; 4. Upgrade toolchain, such as using Vite, esbuild or Rollup to improve the construction speed, although there is migration cost, it has significant effect.
What is the difference between block and inline elements?Jul 23, 2025 am 03:33 AMBlock-level elements occupy one line by default and support full width, while inline elements are displayed in text streams without line breaks. 1. Block-level elements such as, etc. can automatically wrap and width and height can be set; 2. Inline elements such as, etc. are embedded in text streams, width and height settings are usually invalid; 3. The element type can be changed through the display attribute of CSS, such as block, inline-block or flex; 4. Some elements such as and containers using Flexbox/Grid have mixed behavior. Mastering these helps to build a more controllable page layout.
Testing JavaScript Applications with Mocha and ChaiJul 23, 2025 am 03:23 AMUse Mocha and Chai to test JavaScript first to install these two libraries. 1. The installation method is npminstall--save-devmochachai, and create a test folder in the project root directory to store the test files; 2. Configure npmscript such as "scripts":{"test":"mocha"} to start the test through npmtest; 3. Use describe and it to organize the structure of the test cases, and write assertions in combination with expect; 4. Chai supports expect, should and assert, and recommend expe
What is SVG and how to use it in HTML?Jul 23, 2025 am 03:21 AMSVGstandsforScalableVectorGraphics,anXML-basedformatthatusesmathematicalformulasinsteadofpixelstodisplayimagesontheweb.1.SVGsstaysharpatanysize,makingthemidealforlogos,icons,andscalablegraphics.2.Theycanbeeditedwithtexteditors,styledwithCSS,andmanipu


Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment









