WebSocket is a protocol for full-duplex communication on a single TCP connection that HTML5 began to provide.
In the WebSocket API, the browser and the server only need to perform a handshake action, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.
The browser sends a request to the server to establish a WebSocket connection through JavaScript. After the connection is established, the client and the server can directly exchange data through the TCP connection.
After you obtain the Web Socket connection, you can send data to the server through the send() method, and receive the data returned by the server through the onmessage event.
The following API is used to create WebSocket objects.
var Socket = new WebSocket(url, [protocal] );
The first parameter url in the above code, Specify the URL to connect to. The second parameter protocol is optional and specifies acceptable subprotocols.
WebSocket Properties
The following are the properties of the WebSocket object. Suppose we use the above code to create a Socket object:
Properties | describe |
Socket.readyState | The read-only attribute readyState represents the connection status and can be the following values:
|
Read-only property bufferedAmount The number of UTF-8 text bytes that have been put into the queue by send() and are waiting for transmission, but have not yet been sent. |
WebSocket Events
The following are related events for the WebSocket object. Suppose we use the above code to create a Socket object:
Event | Event handler | Description |
Socket. onopen | Triggered when the connection is established | |
Socket.onmessage | Triggered when the client receives data from the server | |
Socket.onerror | Triggered when a communication error occurs | |
Socket .onclose | Triggered when the connection is closed |
Method | Description |
Use the connection to send data | |
Close connection |