Quickly learn about websocket in ten minutes! !

青灯夜游
Release: 2021-02-15 09:18:19
forward
3060 people have browsed it

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
  1. 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
  2. Although http1.1 is enabled by default
  3. keep-aliveLong 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.
  4. Although websocket is a protocol independent of HTTP, websocket must rely on the HTTP protocol for a
  5. 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
socket The word
    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
  1. Application scenarios
  2. 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

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
Copy after login

The following are the differences from traditional HTTP messages:
    Upgrade: websocket
    Connection: Upgrade
    Copy after login
  • indicates that the WebSocket protocol is initiated
  • Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
    Sec-WebSocket-Protocol: chat, superchat
    Sec-WebSocket-Version: 13
    Copy after login

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
Copy after login

    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 Heartbeat

There 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 Ping

Let the server know that it is online, and the server must also reply with a

Heartbeat Pong

to 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:

0: Indicates that the connection is being made

1: Indicates that the connection is successful and communication is possible

2: Indicates that the connection is closing
  • 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

express

and

ws

responsible for processing the WebSocket protocol:

npm install express ws
Copy after login

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(&amp;#39;express&amp;#39;); const SocketServer = require(&amp;#39;ws&amp;#39;).Server; //指定开启的端口号 const PORT = 3000; // 创建express,绑定监听3000端口,且设定开启后在consol中提示 const server = express().listen(PORT, () =&gt; console.log(`Listening on ${PORT}`)); // 将express交给SocketServer开启WebSocket的服务 const wss = new SocketServer({ server }); //当 WebSocket 从外部连接时执行 wss.on(&amp;#39;connection&amp;#39;, (ws) =&gt; { //连接时执行此 console 提示 console.log(&amp;#39;Client connected&amp;#39;); // 对message设置监听,接收从客户端发送的消息 ws.on(&amp;#39;message&amp;#39;, (data) =&gt; { //data为客户端发送的消息,将消息原封不动返回回去 ws.send(data); }); // 当WebSocket的连接关闭时执行 ws.on(&amp;#39;close&amp;#39;, () =&gt; { console.log(&amp;#39;Close connected&amp;#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

  • index.html
<html>
  <body>
    <script src="./index.js"></script>
  </body>
</html>
Copy after login
  • index.js
// 使用WebSocket的地址向服务端开启连接
let ws = new WebSocket(&#39;ws://localhost:3000&#39;);
// 开启后的动作,指定在连接后执行的事件
ws.onopen = () => {
  console.log(&#39;open connection&#39;);
};
// 接收服务端发送的消息
ws.onmessage = (event) => {
  console.log(event);
};
// 指定在关闭后执行的事件
ws.onclose = () => {
  console.log(&#39;close connection&#39;);
};
Copy after login

上面的url就是本机node开启的服务地址,分别指定连接(onopen),关闭(onclose)和消息接收(onmessage)的执行事件,访问html,打印ws信息

打印了open connection说明连接成功,客户端会使用onmessage处理接收

其中event参数包含这次沟通的详细信息,从服务端回传的消息会在event的data属性中。

手动在控制台调用send发送消息,打印event回传信息:

服务端定时发送

上面是从客户端发送消息,服务端回传。我们也可以通过setInterval让服务端在固定时间发送消息给客户端:

server.js修改如下:

//当WebSocket从外部连接时执行
wss.on(&#39;connection&#39;, (ws) => {
  //连接时执行此 console 提示
  console.log(&#39;Client connected&#39;);
+  //固定发送最新消息给客户端
+  const sendNowTime = setInterval(() => {
+    ws.send(String(new Date()));
+  }, 1000);
-  //对message设置监听,接收从客户端发送的消息
-  ws.on(&#39;message&#39;, (data) => {
-    //data为客户端发送的消息,将消息原封不动返回回去
-    ws.send(data);
-  });
  //当 WebSocket的连接关闭时执行
  ws.on(&#39;close&#39;, () => {
    console.log(&#39;Close connected&#39;);
  });
});
Copy after login

客户端连接后就会定时接收,直至我们关闭websocket服务

多人聊天

如果多个客户端连接按照上面的方式只会返回各自发送的消息,先注释服务端定时发送,开启两个窗口模拟:

如果我们要让客户端间消息共享,也同时接收到服务端回传的消息呢?

我们可以使用clients找出当前所有连接中的客户端 ,并通过回传消息发送到每一个客户端 中:

修改server.js如下:

...
//当WebSocket从外部连接时执行
wss.on(&#39;connection&#39;, (ws) => {
  //连接时执行此 console 提示
  console.log(&#39;Client connected&#39;);
-  //固定发送最新消息给客户端
-  const sendNowTime = setInterval(() => {
-    ws.send(String(new Date()));
- }, 1000);
+  //对message设置监听,接收从客户端发送的消息
+   ws.on(&#39;message&#39;, (data) => {
+    //取得所有连接中的 客户端
+    let clients = wss.clients;
+    //循环,发送消息至每个客户端
+    clients.forEach((client) => {
+      client.send(data);
+    });
+   });
  //当WebSocket的连接关闭时执行
  ws.on(&#39;close&#39;, () => {
    console.log(&#39;Close connected&#39;);
  });
});
Copy after login

这样一来,不论在哪个客户端发送消息,服务端都能将消息回传到每个客户端 : 可以观察下连接信息:

总结 

纸上得来终觉浅,绝知此事要躬行,希望大家可以把理论配合上面的实例进行消化,搭好服务端也可以直接使用测试工具好好玩耍一波

更多编程相关知识,请访问:编程教学!!

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template