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 using
long 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 this
TCP 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!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
