This is the fourth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Web Sockets

WebSockets are an advanced technology. It opens an interactive communication session between the user’s browser and the server. Using this API, you can send messages to the server and receive event-driven responses without having to poll the server for responses.

Web sockets grammar

var aWebSocket = new WebSocket(url [, protocols]);
Copy the code

parameter

url

The URL to connect to; This should be the URL to which the WebSocket server will respond. You must enter an absolute URL

protocols

A protocol string or an array of protocol strings.

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

The browser sends a WebSocket connection request to the server through JavaScript. After the connection is established, the client and the server can exchange data directly through THE TCP connection. When you get the Web Socket connection, you can send data to the server via the send() method and receive the data returned by the server via the onMessage event.

When the WebSocket is set up, we can listen for socket events:

The event What is happening
open Connection established
message Triggered when a message is received
error Fired when an error occurs, the connection cannot be sustained
close Triggered when the connection is closed
send Send messages using

Create a Web Sockets

let socket = new WebSocket(url);
Copy the code

Once instantiated, the browser creates the connection immediately,

Websocket has said his state of the attribute, as follows: | — – | — – | | OPENING (0) | is establishing connection | | OPEN (1) | | established connection | CLOSING (2) | is CLOSE the connection | | CLOSE (3) | | has closed connection

To close a socket, call the close() method socket.close() at any time.

After calling close(), the status value becomes 2, and after closing, it becomes 3

2. Send and receive data

After the WebSocket is opened, it can send and receive data for use

let socket = new WebSocket(url);
socket.send('hello word');
Copy the code

Receive data

socket.onmessage = function(event) {
 let data =  event.data;
};
Copy the code

Websockets can only send simple data over a connection. The responsible array needs to serialize the data, and the data returned is a string, just like the data sent to the server through send(). If you want other data formats, you need to parse them manually.

3. Other events

  • Open Triggered when the connection is successfully established
  • Error is emitted when an error occurs. The connection cannot be sustained
  • Close Triggered when the connection is closed

After that, we can simply write a demo to implement persistent communication. Here, we use Node to set up services:

var WebSocketServer = require('ws').Server, wss = new WebSocketServer({ port: 8800 }); wss.on('connection', function (ws) { console.log('client connected'); ws.on('message', function (message) { console.log(message); Ws. Send (" the server receives the message and returns "); }); })Copy the code

WebSocket front-end code;

</button> let url = 'ws://localhost:8800/ws' let socket = new WebSocket(URL); // send message from the form document.getElementsByTagName("button")[0].onclick = function(){ socket.send('hello word'); } // handle incoming messages socket.onmessage = function(event) { console.log(event); };Copy the code

Let’s click to see the execution result. The result is shown in the figure below:

When you click submit, the back end returns the data that we’ve written to,

Let’s look at the node background result:

After receiving the data passed by the front end, return the data to the front end.

Now let’s deal with the data coming through the front end

We return the data that was passed by the front end:

ws.on('message', function (message) {
    let data = message.toString()
    ws.send(data);
});
Copy the code

Then display the returned data in the list:

socket.onmessage = function(event) {
  console.log(event);
  let incomingMessage = event.data;
  showMessage(incomingMessage);
};
function showMessage(message) {
  let messageElem = document.createElement('div');
  messageElem.textContent = message;
  document.getElementById('messages').prepend(messageElem);
}

Copy the code

The result is as follows: Each click is requested to the back end, and the back end returns data. Let’s see what happens:

Then we dynamically modify the data that is passed by the front end by adding an input box

You can also open multiple pages for simple chat room functions:

Open multiple pages and enter different content on different pages. The content on multiple pages will be synchronized.

I’ll put the code down here, if you like

Code address >>> simple chat

Code word is not easy, I hope the big guy Pointers!