Once you understand the network socket connection to the WEB server, you will be able to send data from the browser to the server and receive response data back from the server.
The following is the API to create a new WebSocket object:
var Socket = new WebSocket(url, [protocal] );
The first parameter here refers to the URL to be connected, and the second parameter is optional, if needed If so, specify a protocol supported by the server.
WEB Socket properties:
Attribute |
Description |
Socket.readyState |
readyState represents the connection status of the ReadOnly attribute. It can have the following values:
-
属性 |
说明 |
Socket.readyState |
readyState的代表的ReadOnly属性的连接状态。它可以有以下值:
-
一个0值表示该连接尚未建立。
-
值为1表示连接建立和沟通是可能的。
-
值为2表示连接是通过将结束握手。
-
值为3表示连接已关闭或无法打开。
|
Socket.bufferedAmount |
读属性的bufferedAmount代表文本的字节数,utf - 8的排队使用send()方法。 |
A value of 0 indicates that the connection has not yet been established.
-
A value of 1 indicates that connection establishment and communication is possible.
-
A value of 2 indicates that the connection is through and the handshake will end.
事件 |
处理程序 |
说明 |
open |
Socket.onopen |
此事件发生在套接字建立连接。 |
message |
Socket.onmessage |
此事件发生时,客户端收到来自服务器的数据。 |
error |
Socket.onerror |
此事件发生时有任何通信错误。 |
close |
Socket.onclose |
此事件发生在连接关闭。 |
-
A value of 3 indicates that the connection is closed or cannot be opened.
|
Socket.bufferedAmount |
The bufferedAmount of the read attribute represents the number of bytes of the text, and the queue of UTF-8 uses the send() method. |
WEB Socket event:
方法 |
说明 |
Socket.send() |
send(data)方法用来连接传输数据。 |
Socket.close() |
close()方法将被用于终止任何现有的连接。 |
WEB Socket method:
Copy code
The code is as follows: