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
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
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.
(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.
Application scenariosWebsocket 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
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
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 PingWebSocket StatusThe readyState attribute in the WebSocket object has four states:
responsible for processing the WebSocket protocol:
npm install express ws
installation Package.json after success: Then create the server.js file in the root directory:
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;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><div class="contentsignin">Copy after login</div></div>
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
<html> <body> <script src="./index.js"></script> </body> </html>
// 使用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!