This is the third day of my participation in Gwen Challenge

Introduction to WebSocket objects

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 a response.

What is a WebSocket object?

The WebSocket object is one of the WebSockets interfaces used to connect to the WebSocket server’s main interface over which data can then be sent and received.

The WebSocket object provides an API for creating and managing WebSocket connections and for sending and receiving data over that connection.

Use the WebSocket() constructor to construct a WebSocket:

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

Parameter analysis:

  • Url: the URL to connect to; This should be the URL that the WebSocket server will respond to.
  • Protocols (Optional) : A protocol string or an array containing protocol strings. These strings are used to specify subprotocols so that a single server can implement multiple WebSocket subprotocols (for example, you might want one server to be able to handle different types of interactions based on the protocol specified). If no protocol string is specified, an empty string is assumed.

The constant of the WebSocket object

Constant Value
WebSocket.CONNECTING 0
WebSocket.OPEN 1
WebSocket.CLOSING 2
WebSocket.CLOSED 3

Properties of the WebSocket object

WebSocket.binaryType

Returns the type of binary data transferred over the WebSocket connection.

Grammar:

const binaryType = aWebSocket.binaryType;
Copy the code

Return value: DOMString (a UTF-16 string)

  • "blob": If the transmission isBlobType of data.
  • "arraybuffer": If the transmission isArrayBufferType of data.

WebSocket.bufferedAmount(read-only)

The number of bytes used to return data that has been queued by the send() method but has not yet been sent to the network.

This property value is reset to 0 once all data in the queue has been sent to the network.

However, if the connection is closed during sending, the property value is not reset to 0. If you keep calling send(), the value of this property will keep growing.

Grammar:

const bufferedAmount = aWebSocket.bufferedAmount;
Copy the code

Return value: integer.

WebSocket.extensions(read-only)

Returns the extended value selected by the server. Currently, the only extension values a link can agree to are an empty string or an extension list.

const extensions = aWebSocket.extensions;
Copy the code

Return value: DOMString.

WebSocket.onclose

Returns an event listener that is called when the readyState of the WebSocket connection becomes CLOSED and receives a CloseEvent named “Close”.

Grammar:

WebSocket.onclose = function(event) {
  console.log("WebSocket is closed now.");
};
Copy the code

Return value: EventListener.

WebSocket.onerror

In this property, you can define a callback function to execute when an error occurs. The event name of this event is “error”.

Grammar:

WebSocket.onerror = function(event) {
  console.error("WebSocket error observed:", event);
};
Copy the code

Return value: EventListener.

WebSocket.onmessage

This property is an Event Handler that is invoked when a message is received from the server. It is called by a MessageEvent.

grammar

aWebSocket.onmessage = function(event) {
  console.debug("WebSocket message received:", event);
};
Copy the code

Return value: EventListener.

WebSocket.onopen

This property defines an event handler that is called when the WebSocket’s connection state readyState changes to 1. This means that the current connection is ready to send and receive data. This event handler is fired by an event (when a connection is established).

Grammar:

aWebSocket.onopen = function(event) {
  console.log("WebSocket is open now.");
};
Copy the code

Return value: EventListener.

WebSocket.protocol(read-only)

Used to return the name of the subprotocol selected on the server side; This is a string specified in the parameter Protocols when the WebSocket object is created, empty if there are no established links.

Grammar:

var protocol = aWebSocket.protocol;
Copy the code

Return value: DOMString.

WebSocket.readyState(read-only)

Returns the link status of the current WebSocket, read-only.

Grammar:

var readyState = WebSocket.readyState;
Copy the code

Value:

  • 0 (WebSocket.CONNECTING) is linking
  • 1 (WebSocket.OPEN) has been linked and can communicate
  • 2 (WebSocket.CLOSINGThe connection is closing
  • 3 (WebSocket.CLOSEDConnection closed or failed

WebSocket.url(read-only)

The return value is the absolute path to the URL when the constructor creates the WebSocket instance object.

Grammar:

var url = aWebSocket.url;
Copy the code

Return value: DOMString.

Method of the WebSocket object

WebSocket.close()

Method to close a WebSocket connection or connection attempt, if any. This method does nothing if the connection is already closed.

Grammar:

WebSocket.close();
Copy the code

Parameters:

  • code(Optional) A numeric status code that explains why the connection is closed. If this parameter is not passed, 1005 is used by default.
  • reason(Optional) A human-readable string that explains why the connection is closed. The UTF-8 encoded string cannot exceed 123 bytes.

WebSocket.send()

Method queues the data that needs to be transferred to the server over the WebSocket link and increases the value of bufferedAmount based on the size of the data bytes that need to be transferred. If the data cannot be transferred (for example, if the data needs to be cached and the buffer is full), the socket closes itself.

Grammar:

WebSocket.send("Hello server!");
Copy the code

Parameters:

Data Data transferred to the server. It must be one of the following types:

  • USVStringText string. The string is added to the buffer in UTF-8 format, andbufferedAmountWill add the value of the number of bytes encoding the string in UTF-8 format
  • ArrayBufferYou can send the underlying binary data using a typed array object; Its binary data memory will be cached in a buffer,bufferedAmountThe value of the required number of bytes will be added.
  • BlobThe Blob type transmits the raw data in the queue Blob in binary.bufferedAmountThe value of the number of bytes of the original data will be added.
  • ArrayBufferViewYou can send any as a binary frameJavaScript class array object; Its binary data content will be queued into a buffer. valuebufferedAmountThe value of the necessary number of bytes will be added.

Event of a WebSocket object

The WebSocket object listens for the following events using addEventListener() or by assigning an event listener to the interface’s ON * EventName * property.

close event

The close event is emitted when the connection to the WebSocket is closed.

You might want to know when the connection is closed so you can update the UI or save data related to the closed connection. Example:

exampleSocket.addEventListener('close'.(event) = > {
  console.log('The connection has been closed successfully.');
});
Copy the code

error event

An error event is raised when a Websocket connection is closed due to some error event (such as an inability to send some data). Example:

// Create WebSocket connection
// Create a WebSocket connection
const socket = new WebSocket('ws://localhost:8080');

// Listen for possible errors
// Listen for possible errors
socket.addEventListener('error'.function (event) {
  console.log('WebSocket error: ', event);
});
Copy the code

message event

The Message event is raised when the WebSocket receives a new message. Example:

// Create a WebSocket connection
const socket = new WebSocket('ws://localhost:8080');

// Listen for messages
socket.addEventListener('message'.function (event) {
    console.log('Message from server ', event.data);
});
Copy the code

open event

Triggered when a WebSocket connection succeeds. It can also be set via the onopen property. Example:

// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open'.(event) = > {
  socket.send('Hello Server! ');
});
Copy the code

Learn interesting knowledge, meet interesting friends, shape interesting soul!

Everybody is good! I am the author of programming Samadhi, yi Wang, my public account is “programming Samadhi”, welcome to pay attention to, I hope you can give me more advice!