Summary of the websocket

Websocket is a communication protocol, which is a persistent TCP connection between the server and the client. Any client and server can use this protocol, but it is primarily the browser and server. Through Websocket, the server can actively pass data to the client, without the client initiating the request like HTTP.

Websocket client usage


const socket = new WebSocket('websocket url');


// The event function
socket.onopen = function(e) {
   
}

socket.onmessage = function(e) {

}

socket.onclose = function(e) {

}

socket.onerror = function(e) {}// Read-only attribute
socket.url
socket.protocol
socket.extensions
socket.bufferedAmount

// Read-write attributes
socket.binaryType
socket.readyState


// Function properties
socket.close();
socket.send();

Copy the code

Establish a connection

First we need to create an instance of WebSocket. After the instance is created, the connection to the server is already established. Once the connection is established, the listening onOpen event responds. We can test the effect by using the following code.

const socket = new WebSocket('ws://echo.websocket.org');
socket.onopen = function(e) {
  console.log('Connection established')}Copy the code

After establishing a connection, you can view the connection status of the Websocket. State determination is observed through the readyState property. It has these values:

value state describe
0 CONNECTING Connect to the server…
1 OPEN A connection has been established and you can communicate with the server
2 CLOSING Closing the connection…
3 CLOSED closed

Receives the message

The processing of a received message is handled as a callback by an event that receives the message.

 socket.onmessage = function(e) {
   console.log(e)
 }
Copy the code

When the server sends a message to the client, the message event is executed in the bound callback function.

An error occurred

If an error occurs during the communication between the client and the server. The bound error function is executed.

socket.onerror = function(e) {
  console.log("error throw");
}
Copy the code

Connection is closed

When the client and server close the WebSocket connection, a close event is executed

socket.onclose = function(e) {
  console.log('closed');
}
Copy the code

The client actively closes the connection by calling the close function. The onclose event is also executed after the close function is executed.

socket.close()
Copy the code

The close function takes two optional arguments. The first argument is code: the code number, and the second argument is reason: the reason for closing.

socket.close(2100, "Close the question")
Copy the code

Code is a numeric value, and reason is a string of less than 123 bytes.

Send a message

The function that sends a message, directly a send to process.

socket.send("Message content............")
Copy the code

In the process of sending messages, when we send messages, the readyState should be in the open state. Otherwise, the corresponding exception will be thrown.

When sending a message, we can set the type of message to send. This property is binaryType. It has two values: blob and arrayBuffer. By default we are of type arrayBuffer. We can send character types.

socket.binaryType = "arrayBuffer";
Copy the code

In this case, the data we get in onMessage is also an arrayBuffer. You can just print it out.

If we specify theta

socket.binaryType = "blob";
Copy the code

The data we send must also be of binary type: Blob type. We need to construct the relevant data from the Blob object and send it. Such as

const blob = new Blob(["hello, world"])
socket.send(blob);
Copy the code

In the onMessage event, the data retrieved will also be bloB object data.

  socket.onmessage = function(e) { console.log(e.data.text()); // This will be converted to text data}Copy the code

conclusion

In the actual project, we will encounter a variety of different actual connection problems, this requires us to calm down to analyze each step of the process, really understand the implementation of websocket process.

Later, we will write the server side websocket to understand the full use of webSocket.