Network socket is the next generation of two-way communication technology for WEB applications. It is based on an independent socket and requires a client browser to support HTML5. Once you understand the connection between the network socket and the WEB server, you can send data from the browser to the server and receive the response data returned by the server.
The following is an API for creating a new WebSocket object:
The Code is as follows:
Var Socket = new WebSocket (url, [protocal]);
Here, the first parameter refers to the URL to be connected, and the second parameter is optional. If necessary, it is to specify a protocol supported by the server.
WEB Socket attributes:
Attribute |
Description |
Socket. readyState |
ReadyState indicates the connection status of the ReadOnly attribute. It can have the following values:
A value of 0 indicates that the connection has not been established.
1 indicates that connection establishment and communication are possible.
If the value is 2, the connection ends by shaking hands.
If the value is 3, the connection is closed or cannot be opened.
|
Socket. bufferedAmount |
The bufferedAmount of the read attribute indicates the number of bytes of the text. The send () method is used in the utf-8 queue. |
WEB Socket event:
Event |
Handler |
Description |
Open |
Socket. onopen |
This event occurs when a connection is established on the socket. |
Message |
Socket. onmessage |
When this event occurs, the client receives data from the server. |
Error |
Socket. onerror |
Any communication error occurs when this event occurs. |
Close |
Socket. onclose |
This event occurs when the connection is closed. |
WEB Socket method:
Method |
Description |
Socket. send () |
The send (data) method is used to connect to and transmit data. |
Socket. close () |
The close () method is used to terminate any existing connection. |
WEB Socket example:
The Code is as follows: