preface

The server communicates with the client over a long period of time. There are a lot of mature framework can be completed, the bottom is nothing more than the Socket flow encapsulation and use.

First, the SOCKET principle

A Socket is basically an end-to-end connection. These two ends are called sockets.

HTTP is based on TCP protocol at the transport layer, and Socket API is also, so just in terms of usage, Socket and HTTP can be considered similar (HTTP is a written Internet protocol, Socket is always used as a programming concept), is another direct use of the transport layer protocol.

1.1 Socket Concepts

Socket is the cornerstone of communication and the basic operation unit of network communication that supports TCP/IP protocol. It is an abstract representation of an endpoint in the process of network communication, and contains five kinds of information necessary for network communication:

  • Protocol used for connection,
  • IP address of the local host,
  • Protocol port of the local process,
  • IP address of the remote host,
  • Protocol port of the remote process

When the application layer communicates data through the transport layer, TCP encounters the problem of providing concurrent services for multiple application processes. Multiple TCP connections or multiple application processes may need to transfer data over the same TCP protocol port. To distinguish between different application processes and connections, many computer operating systems provide Socket interfaces for applications to interact with TCP/IP. The application layer and the transmission layer can distinguish the communication from different application process or network connection through Socket interface, and realize the concurrent service of data transmission.

1.2 Establishing a Socket Connection

Establishing a Socket connection requires at least one pair of sockets, one of which runs on the client, called ClientSocket, and the other on the server, called ServerSocket.

The connection process between sockets is divided into three steps: server listening, client request, and connection confirmation.

Server listening: The server socket does not locate the specific client socket, but is in the state of waiting for the connection, monitoring the network status in real time, waiting for the connection request of the client.

Client request: a connection request is made by the client socket to the server socket. To do this, the client-side socket must first describe the socket of the server to which it is connecting, specifying the address and port number of the server-side socket, and then make a connection request to the server-side socket.

Connection confirmation: When the server socket listens to or receives a connection request from the client socket, it responds to the request of the client socket by creating a new thread and sending the description of the server socket to the client. Once the client confirms the description, the two sides formally establish a connection. The server socket continues to listen, receiving connection requests from other client sockets.

Note that sockets are not a protocol, but rather a friendly way to provide programming for developers. Socket through the facade mode to achieve the TCP/IP encapsulation, it actually provides a series of interfaces to the upper layer, in order to facilitate our operations in our own applications, without caring about the complex TCP/IP processing. This network layer belongs to the data transport layer.

Second, the WebSocket

WebSocket Protocol is a new protocol for HTML5. At present, except Internet Explorer, other browsers are basically supported. It implements full-duplex communication between the browser and the server. The initial handshake needs to be done with an HTTP request.

His goal was instant messaging, an alternative to polling. Instant messaging on websites is very common, such as QQ, chat system and so on. According to the previous technical ability is usually the use of polling, Comet technology to solve.

2.1 Disadvantages of polling:

HTTP is a non-persistent, one-way network protocol. After a connection is established, the server can only return the corresponding data after the browser sends a request to the server. When instant messaging is required, the browser sends a Request to the server at a specific time interval (such as 1 second) through polling, and then the latest data is returned to the browser.

The most obvious disadvantage of this method is that it needs to continuously send requests, and usually the HTTP request Header is very long. In order to transmit a small amount of data, it needs to pay a huge price, which is very uneconomical and takes up a lot of broadband.

HTTP1.1 uses long connections by default. If HTTP is used for long connections, the following message is added to the response header: Connection:keep-alive

However, the emergence of WebSocket can make up for this shortcoming. In WebSocket, the server and browser only need to shake hands through HTTP protocol, and then establish a SEPARATE TCP communication channel for data transmission.

2.2 the WebSocket principle

WebSocket is also an application-layer protocol like HTTP, but it is a two-way communication protocol built on TOP of TCP.

WebSocket is a protocol for full duplex communication over a single TCP connection. The WebSocket API is also a W3C standard.

WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

Handshake process:

  1. The browser and server establish a TCP connection and shake hands for three times. This is the basis of communication, the transport control layer, and if it fails, it doesn’t execute.
  2. After the TCP connection succeeds, the browser sends information such as the version number supported by WebSocket to the server through HTTP. (HTTP handshake before starting)
  3. After receiving the handshake request from the client, the server also uses HTTP to send back data.
  4. After receiving a successful connection message, communication is transmitted through the TCP channel.

The default Websocket request protocol is ws:// and the default port is 80. The request protocol for TLS encryption is WSS ://, port :443.

2.3 Relationship between webSocket and HTTP

Similarities:

  1. It’s all the same TCP based, it’s all reliability transport protocol.
  2. Both are application layer protocols.

Difference:

  1. WebSocket is a two-way communication protocol that simulates the Socket protocol and can send or receive information in both directions.
  2. HTTP is one-way.
  3. WebSocket requires a handshake to establish a connection.

Contact: When WebSocket establishes a handshake, data is transmitted over HTTP. However, once established, the HTTP protocol is not required for actual transmission.

2.4 Relationship between WebSocket and Socket

Socket is not a protocol, but a layer abstracted to facilitate the use of TCP or UDP. It is a group of interfaces between the application layer and the transmission control layer. TCP is a reliable connection, and data can be sent only after the connection. Udp is an unreliable connection and can send numbers without a connection.

Socket is the intermediate software abstraction layer of communication between application layer and TCP/IP protocol family. It is a group of interfaces. In the design mode, Socket is actually a facade mode, it hides the complex TCP/IP protocol family behind the Socket interface, for the user, a simple set of interfaces is all, let the Socket to organize data to conform to the specified protocol.

When two hosts communicate with each other, they must be connected through a Socket, which uses TCP/IP to establish a TCP connection. TCP connections rely on the underlying IP protocol, and IP connections rely on the link layer and other lower layers.

WebSocket is a typical application layer protocol. Socket is a transport control layer protocol.

2.5 WebSocket Features and Common Concepts

  • Supports browser /Nodejs environment
  • Support for two-way communication
  • Easy to use API
  • Support binary transmission
  • Reduce the amount of data transferred

2.5.1 long polling

HTTP long polling allows the server to immediately respond to a request if it has data. If there is no data, it will hold for a period of time. If there is data during this period, it will immediately respond to the request. If the time is up and there is no data, respond to the HTTP request; The browser receives the HTTP response and immediately sends the same HTTP request to see if there is data;

2.5.2 Short Polling:

No matter whether the client receives the response data from the server, the client periodically sends requests to the server to check whether the data is updated. The limitation of HTTP short polling is its low real-time performance.

The similarities between long polling and short polling can be seen: HTTP long polling and HTTP short polling will hold for a period of time;

The difference between long polling and short polling occurs on the server or browser side. HTTP long polling holds for a period of time on the server side, while HTTP short polling holds for a period of time on the browser side. Application: HTTP long polling is generally used in Web IM, which requires high real-time performance. The control of HTTP long polling is always on the server side, while the data is on the server side, so it has high real-time performance.

HTTP short polling is generally used in places where real-time requirements are not high, such as sina weibo’s unread number of queries is the browser end at intervals. SetInterval

2.5.3 long connection

  1. A long connection refers to a TCP connection, not an HTTP connection
  2. A long connection means that the connection will be reused
  3. Connection: keep-alive is set for both the server and client
  4. HTTP1.1 is the default long connection protocol

The so-called HTTP long connection is a TCP connection shared by multiple HTTP requests. In HTTP 1.1, the connection field is used in the request header and the corresponding header to identify whether the long CONNECTION is HTTP. Keep-alive indicates an HTTP long connection. Connection :closed: indicates that the TCP connection is closed.

Timeout =30, Max =5, timeout is the time to hold two HTTP requests (s), Max is that this TCP connection can be reused for at most a few HTTP requests

Multiple packets can be sent over a TCP connection. If no packets are sent during the TCP connection, heartbeat packets need to be sent to maintain the connection. Connection process: Establish connection — data transfer –… Send heartbeat packet, maintain connection. — Data transfer — Close the connection

Benefits:

For example, request a common web page, the web page must contain a number of CSS, JS and a series of resources, if it is a short connection (that is, each time to re-establish the TCP connection), then open a web page each time, the basic will establish several or even dozens of TCP connections, waste a lot of network resources. If it is a long connection, then so many HTTP requests (including requests for web page content, CSS files, JS files, images, etc.) are using a TCP connection, which can obviously save a lot of resources.

Another point is that long connections are not permanent. If no HTTP request has been sent for a period of time (which can be set in the header, known as the timeout), the long connection will be broken.

Note: Since HTTP1.1, connections are long by default. There is no short connection (HTTP1.0 uses short connections by default), and most short and long connections on the web are essentially TCP connections.

2.5.4 short connection

A TCP connection is established when two communication parties interact with each other. After data is sent, the connection is disconnected. Connection process: Establish connection — data transfer — Disconnect –… — Establish a connection — Transfer data — disconnect

The current version of THE HTTP protocol is 1.1, and the previous version was 1.0. One difference between the two is that 1.1 supports HTTP long connections

Http1.0 does not support HTTP long connections. After each HTTP request response, the TCP connection is closed and re-established for the next HTTP request.

2.5.5 Communication Concepts

  • simplex

Data can only be transmitted in a single fixed direction from the sender to the receiver.

  • Half duplex

The two parties are both receivers and senders, but only one direction is allowed at a time.

  • Full duplex:

That is, the two devices can send and receive data at the same time.

Simplex, half-duplex, and full-duplex are all based on the TCP protocol (transport layer) and are not to be confused with the application layer.

Three, HTTP and TCP difference and connection

3.1. TCP Connection

Setting up a TCP connection requires a three-way handshake:

First handshake: The client sends a SYN packet (SYN = J) to the server and enters the SYN_SEND state.

Second handshake: After receiving a SYN packet, the server must acknowledge the client’s SYN (ACK = J +1) and send a SYN packet (ACK = K). In this case, the server enters the SYN_RECV state.

Third handshake: After receiving the SYN+ACK packet from the server, the client sends an ACK packet (ACK = K +1) to the server. After the packet is sent, the client and the server enter the ESTABLISHED state to complete the three-way handshake.

The packet transmitted during the handshake does not contain data. After three handshakes, the client and server start data transmission. Ideally, once a TCP connection is established, it is maintained until either of the communicating parties voluntarily closes the connection. During disconnection, both the server and the client can initiate a request to disconnect the TCP connection. The disconnection process requires “four handshakes”.

3.2. HTTP Connection

HTTP, also known as Hypertext Transfer Protocol, is the foundation of Web networking and one of the protocols commonly used in mobile networking. HTTP is an application based on TCP.

The most remarkable feature of HTTP connections is that each request sent by the client requires a response from the server, and when the request is complete, the connection is released. The process from establishing a connection to closing a connection is called one connection.

1) In HTTP 1.0, each request from the client required a separate connection, which was automatically released after the request was processed.

2) In HTTP 1.1, multiple requests can be processed in a single connection, and multiple requests can be overlapped without waiting for one request to finish before sending the next.

Because HTTP actively releases the connection at the end of each request, an HTTP connection is a “short connection” that requires continuous connection requests to the server to keep the client program online. The usual practice is that even without obtaining any data, the client also keeps sending a “stay connected” request to the server at regular intervals. After receiving the request, the server replies to the client, indicating that it knows the client is “online”. If the server cannot receive requests from the client for a long time, the client is considered offline. If the server cannot receive any reply from the server for a long time, the network is disconnected.

  • TCP is a low-level communication protocol that defines the data transmission and connection mode

  • HTTP is an application layer protocol that defines the specification of the content of data transmission

  • HTTP data is transmitted using TCP protocol, so support HTTP must support TCP

  • HTTP supports WWW services;

  • The TCP/IP protocol is the foundation of the Internet. TCP/IP is the basic communication protocol used in networks.

Nodejs creates a Web server and Tcp server

4.1 Creating a Web Server Using Express

var express = require('express'); var app = express(); app.use(express.static('./public')) app.get('/',(req,res,next)=>{ res.end('hello'); next(); Var Router = express.router (); var Router = express.router (); Router.get('/add',(req,res)=>{ res.end('add') }) Router.get('/list',(req,res)=>{ res.end('list') }) app.use('/post', Router) //route ('/article').get((req,res)=>{res.end('/article get')}).post((req,res)=>{ res.end('/article post') }) app.get('/news/:newsId', (req, res)=>{ req.end('newsId:' + req.newsId); }) app.listen(18001, function afterLister(){console.log(' service started again ')})Copy the code

4.2 Creating a TCP Server

To create a TCP server using Node.js, first use require (‘ NET ‘) to load the NET module, and then use the createServer method of the NET module to create a TCP server.

  • Create a TCP server using the NET module
  • Use Telnet to connect to the TCP server
  • Create a TCP client using NET

The following code builds a TCP server:

Var net=require('net'); Var server= net.createserver (function(socket){console.log('someone connets'); }) server.listen(18001,function(){ console.log('server is listening'); });Copy the code

When you type http://localhost:18001/ in the browser, someone connets is displayed, indicating that the callback function of the createServer method has been executed, indicating that the TCP server has been successfully connected.

Server: tcp.js:

Const HOST = '127.0.0.1; Var net=require('net'); Var server= net.createserver (function(socket){console.log('someone connets'); // // Obtain address information var address=server.address(); Console. log(' The port is '+address.port); console.log('the address is '+address.address); var message='client,the server address is'+JSON.stringify(address); Write (message,function(){var writeSize= socket.byteswritten; console.log(message+'has send'); console.log('the size of message is'+writeSize); }); On ('data',function(data){// Print data console.log(data.tostring ()); socket.write('server write:test ') }); }); Server.listen (18001,HOST,function(){console.log('server is listening'); });Copy the code

Start the service node tcp.js

The client CMD

1> On the CMD console, enter Telnet 127.0.0.1 18001 to simulate the client

However, you need to check Telnet through the control panel first, as shown in the picture below:

2> Or through the network debugging assistant to simulate client and server debugging

Network Debugging Assistant debugging download address:

Link: https://pan.baidu.com/s/1bZQm1f9UtBKPSAIyqM4Nyw extraction code: d9ckCopy the code

Reference: www.onlinedown.net/soft/971066…

Tcpclient.js:

var net = require('net') const PORT = 18001; Const HOST = '127.0.0.1; var tcpClient = net.Socket(); Tcpclient.connect (PORT, HOST, function(){console.log(' the client sent the message successfully ') tcpClient.write(' the client sent the message successfully ')}); tcpClient.on('data',(data)=>{ console.log( data.toString()) })Copy the code

Five, websocket common framework

  • socket.io
  • Ws

5.1 WebSocket Events:

The WebSocket API is purely event-driven and can handle incoming data and changing link state by listening for events. The client does not need to rotate the server to update the data. After the server sends the data, messages and events arrive asynchronously. WebSocket programming follows an asynchronous programming model that simply adds callbacks to WebSocket objects to listen for events. You can also use the addEventListener() method to listen. A WebSocket object has four different types of events.

5.1.1 open:

Once the server responds to the WebSocket connection request, the open event is emitted. The callback function that responds is called onopen.

ws.onopen = function(e) { console.log("Connection open..." ); };Copy the code

When the open event is raised, it means that the protocol handshake is complete and the WebSocket is ready to send and receive data. If your application receives an open event, you can be sure that the server has processed the connection request and agreed to communicate with your application.

5.1.2 Message

When a message is received, a message event is triggered, and the response callback function is called onMessage. // An event handler that receives a text message:

ws.onmessage = function(e) { if(typeof e.data === "string"){ console.log("String message received", e, e.data); } else { console.log("Other message received", e, e.data); }};Copy the code

In addition to text messages, the WebSocket message mechanism can also handle binary data. There are two types of data, Blob and ArrayBuffer, which need to be determined before reading the data.

// Set the binary data type to blob (the default type) ws.binaryType = "blob"; // Event handler for receiving Blob messages ws.onmessage = function(e) { if(e.data instanceof Blob){ console.log("Blob message received", e.data); var blob = new Blob(e.data); }}; //ArrayBuffer ws.binaryType = "arraybuffer"; ws.onmessage = function(e) { if(e.data instanceof ArrayBuffer){ console.log("ArrayBuffer Message Received", + e.data); Var a = new Uint8Array(e.da); }};Copy the code

5.1.3 the Error

An error event, called onError, is raised if an unexpected failure occurs, and the error causes the connection to close. If you receive an error event, you will soon receive a close event, in which you may be told the reason for the error. The handling of error events is more suitable for reconnection logic.

Ws. onError = function(e) {console.log("WebSocket Error: ", e); };Copy the code

5.1.4 ensuring Close

This event is automatically triggered when the connection is closed, corresponding to the onClose method. After the connection is closed, the server and client cannot send or receive messages. Of course you can call the close method to disconnect from the server and trigger the onclose event,

ws.onclose = function(e) {
    console.log("Connection closed", e);
};
Copy the code

5.2 WebSocket Method:

5.2.1 the send

Once a full-duplex bidirectional connection has been established between the server and client, the send method can be used to send a message, and a text message ws. Send (“Hello WebSocket!”) );

The send() method sends data when the connection is open and throws an exception when the connection is closed or unavailable.

Note: Data can be sent only after it is open

var ws = new WebSocket("ws://echo.websocket.org")
ws.onopen = function(e) {
    ws.send("Initial data");
}
Copy the code

If you want to send a message in response to another event, check if the readyState property is open.

Function myEventHandler(data) {if (ws.readyState === websocket.open) {ws.send(data); } else { // Do something else in this case. } }Copy the code

Sending binary data:

// Send a Blob var blob = new Blob("blob contents"); ws.send(blob); // Send an ArrayBuffer var a = new Uint8Array([8,6,7,5,3,0,9]) ws.send(a.buffer);Copy the code

Blob objects are quite useful when used with the JavaScript File API to send or receive files, most multimedia files, images, video, and audio files. The chapter ends with the File API providing example code that reads the contents of a File to send a WebSocket message.

5.2.2 the close ()

Use the close method to close the connection, which does nothing if it is connected and closed. After calling the close method, data cannot be sent. ws.close();

6. Websocket server building based on WS

1. Simple installation

NPM install WS

Ws: is a WebSocket library of NodeJS that can be used to create services.

Ws github address

The WebSocket protocol defines two URL schemes, WS and WSS representing unencrypted and encrypted communication between client and server respectively. WebSocket (WS) is similar to Http URL, while WebSocket Security (WSS) URL indicates that the connection is based on TLS/SSL, which is the same Security mechanism as HTTPS connection.

2. Configure server.js on the server

Create a new server.js file in the project, create the service, specify port 8181, and log the received messages.

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 8181 });
wss.on('connection', function (ws) {
    console.log('client connected');
    ws.on('message', function (message) {
        console.log(message);
    });
});

Copy the code

The complete server code is as follows:

var WebSocket = require('ws').Server; Let WSS = new WebSocket({port:8181}) // WSS emitters eventWss. on(' Connection ',function(ws) Ws. on('message',function(data){console.log(data); }) ws.on('close',function(){console.log(' close')})});Copy the code

3. Set up a WebSocket link on the client client

We need to create a WebSocket connection by calling the WebSocket constructor, which returns an instance of WebSocket that can be used to listen for events. These events will tell you when a connection is established, when a message arrives, when the connection is closed, and when an error occurred.

The WebSocket constructor requires a URL parameter and an optional Protocol parameter (the name of one or more protocols), such as XMPP, Simple Object Access Protocol (SOAP), or a custom Protocol. The URL parameter must start with WS:// or WSS://, for example, WS:// www.websocket.org

Establish a WebSocket connection on the page. Use send to send messages.

var ws = new WebSocket("ws://localhost:8181");
    ws.onopen = function (e) {
        console.log('Connection to server opened');
    }
    function sendMessage() {
        ws.send($('#message').val());
    }

Copy the code

The complete code is as follows:

  <input class="form-control" type="text" name="message" id="message"
            placeholder="Type text to echo in here" value="" />
            <button type="button" id="send" class="btn btn-primary" onclick="sendMessage();">
            Send!
        </button>
<script>
         // Native IE9 is not supported
        var ws = new WebSocket("ws://localhost:8181");
            ws.onopen = function (e) {
                console.log('Connection to server opened');
                let msg = {type:'test'.id:1.info:'laney'}
                ws.send(JSON.stringify(msg));
                console.log("sened a laney");
            }
            function sendMessage() {
                var message = document.getElementById('message');
                // ws.send(message.value); // Send information to the back end

                ws.send(JSON.stringify({type:'test1'.id:1.info:message.value}))
            }
            // The request from the server is received
            ws.onmessage = function (e) {
                console.log(e.data);
            }

            </script>  
Copy the code

After running as follows, the server immediately gets the message from the client.

7. Build websocket server based on socket. IO

Socket. IO is one of many Websocket libraries. It does not simply implement Websocket like other libraries, but wraps a thick layer around websocket. Socket. IO defines a webSocket-based protocol, so the server and client of socket. IO must be compatible. In short, if the server uses socket. IO, the client has no choice but to use the socket. IO client as well.

  • Socket. IO is a wrapped library based on engine. IO
  • Socket. IO is a Client-Server real-time communication library based on Websocket.
  • The socket. IO layer uses engine. IO to encapsulate a protocol.

Socket. IO provides a Namespace concept. When the client creates a new long connection, a new Namespace is assigned to distinguish between them.

7.1 socket. IO events

7.1.1 System events of the socket. IO server

IO. On (‘connection’, callback): when a new Socket connection is established socket.on(‘message’, callback): when a Socket.. The send() method fires socket.on(‘disconnect’, callback): fires when the connection is disconnected

7.1.2 System Events on the Client

Socket. IO. On (‘ open ‘, the callback) : Trigger socket.io. On (‘ connect ‘, callback): Trigger socket.io. On (‘ connect_timeout ‘, callback) when the socket client connects to the server. Callback): Trigger socket.io. On (‘ connec_errort ‘, Callback): trigger socket.io. On (‘ connec_attemptt ‘, Callback): trigger socket.io. On (‘ reconnect ‘, Callback): trigger socket.io. On (‘ reconnect_error ‘, On (‘ reconnect_fail ‘, callback): Triggers socket.io. On (‘ close ‘, callback): triggers socket.io. Callback): Triggered when the socket client closes the connection with the server

7.2 Native NodeJS and socket. IO realize communication between server and client

IO/socket.io/socket.io/socket.io/socket.io/socket.io/socket.io/socket.io/socket.io/socket.io/socket.io/socket.io/socket.io/socket.io 3. The server broadcasts through emit and receives broadcasts through ON. 4. The client broadcasts through EMIT and receives broadcasts through ON

WebSocket Protocol is a new protocol for HTML5. It implements full duplex communication between browser and server, and allows cross-domain communication. It is a good implementation of server push technology. We use socket. IO, which nicely encapsulates the webSocket interface, provides a simpler, flexible interface, and provides backward compatibility for browsers that do not support webSocket.

7.2.1 Why is WebSocket Needed

HTTP protocol is a stateless, connectionless, unidirectional application-layer protocol. It uses a request/response model. The communication request can only be initiated by the client, and the server responds to the request.

One drawback of this communication model is that the HTTP protocol does not allow the server to initiate messages to the client.

7.2.2 Specific steps and usage

1. Install socket. IO

Address: socket. IO /

NPM install socket. IO or yarn add socket. IOCopy the code

2. Create a server and create an IO object.

var http = require('http'); var path = require('path'); var fs = require('fs'); IO var socket = require('socket. IO '); Var app = http.createserver (function(req,res){// Load static pages fs.readFile(path.resolve(__dirname,'app.html'),function(err,data){ if(req.url=="/"){ res.writeHead(200,{"Content-Type":"text/html; charset='utf-8'"}); res.end(data); Var IO = socket(app); IO. On ('connection',function(sock){console.log(sock) console.log(' server established connection'); }) app. Listen (3000, '127.0.0.1);Copy the code

Socket with the HTTP service after the connection is established, you will find that http://127.0.0.1:3000/socket.io/socket.io.js is the address of a js file.

Now you need to create a client-side index page that must reference the secret JS file. Call IO to get the socket object.

index.html

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>The client</title>
    <script src="http://localhost:3000/socket.io/socket.io.js"></script>
</head>
<body>
    
    <script>
      var socket = io('http://localhost:3000/');  /* Establish a connection with the server */
    </script>
</body>
</html>

Copy the code

At this point it will print “a client has established a connection with the server” at the terminal.

3. The server broadcasts through emit and receives broadcasts through ON

IO var socket = require('socket. IO '); Var IO = socket(app); IO. On ('connection',function(sock){console.log(' a client has established a connection with the server '); On ('addcart', function(data){console.log(data); // the server sends data to the client //socket.emit(); */ // IO. Emit (); /* Emit emit data to all clients */ socket.emit('to-client',' I am server data '+data.client); // IO. Emit ('to-client',' I am server data '+data.client); }) sock.on('disconnect',function(){console.log(' disconnect'); })})Copy the code

Each connected user has a socket. Since our emit statement is issued by socket.emit(), we refer to issuing a statement to this client.

To broadcast is to send a message to all currently connected users:

IO. Emit ('to-client',' I am server data '+data.client); /* All clients connected to the server broadcast data */Copy the code

4. The client broadcasts through emit and receives broadcasts through ON

 <button id="button">Send data to the server</button>
    <script src="http://localhost:3000/socket.io/socket.io.js"></script>
    <script>
      var socket = io('http://localhost:3000/');  /* Establish a connection with the server */

      socket.on('connect'.function(){
            console.log('Client and server are connected');
      })

      socket.on('disconnect'.function(){
            console.log('Client and server are disconnected');
      })


      var btn=document.getElementById('button');
      btn.onclick= function () {
                // The client sends data to the server
                socket.emit('addcart', {client:'I'm data on the client.'})}// Listen for server broadcasts
      socket.on('to-client'.function(data){
         console.log('The server says :'+data)
       })

    </script>

Copy the code

7.3 Express Communicates with socket. IO between the server and the client

The first goal is to create a simple HTML web page that provides forms and a list of messages.

var app = require('express')(); Var HTTP = require(' HTTP ').createserver (app); //var http = require('http').Server(app); app.get('/', (req, res) => { res.send('<h1>Hello world</h1>'); }); http.listen(3000, () => { console.log('listening on *:3000'); });Copy the code

Express initializes the app as a function handler that can be provided to the HTTP server. We define a routing handler that is called when we visit the home page of our website.

We let the HTTP server listen on port 3000.

7.3.1 into the Socket. IO

npm install socket.io

Note: Socket. IO is based on the HTTP server.

var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');
});

http.listen(3000, () => {
  console.log('listening on *:3000');
});
Copy the code

7.3.2 Writing Socket code

IO. On ('connection', function (socket) {console.log('a user connected'); socket.on('message',function(key){ console.log(key); IO. Emit ('servermessage',data); // IO. /* Server sends data to client */ // robot chat // console.log(robot[key]) // socket.emit('servermessage',robot[key]); io.emit('servermessage',key.msg); })});Copy the code

7.3.3 group chat

IO. Emit broadcast As soon as it receives a message from the client, it sends this message to all client users connected to the service

io.emit(‘servermessage’,data); / The server sends data to the client /

7.3.4 Robot chat

Socket. emit who sent me the message I will return to the specific code as above:

socket.emit('servermessage',robot[key]);
Copy the code

7.3.5 Client Code

<ul id="messages"> </ul> <form > <input id="msg" autocomplete="off" /><button id="send" >Send</button> </form> <script SRC = "https://code.jquery.com/jquery-3.4.1.min.js" > < / script > < script SRC = "/ socket. IO/socket. IO. Js" > < / script > < script > var  socket = io(); / / group chat function - chat rooms $(' # send). Click (function (e) {e.p reventDefault (); var msg=$('#msg').val(); // socket.emit('message',msg); // / emit('message',{name:'laney', MSG: MSG}); Socket. on(' serverMessage ',function(data){console.log(data) $('#messages').append(`<li>${data}<li>`) }) </script>Copy the code

Reference:

https://github.com/websockets/ws
https://www.cnblogs.com/chyingp/p/6072338.html
https://www.cnblogs.com/tzyy/p/5124256.html
Copy the code