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:
Copy codeThe 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:
Copy codeThe Code is as follows:
<! Doctype html>
<Html>
<Head>
<Script type = "text/javascript">
Function WebSocketTest ()
{
If ("WebSocket" in window)
{
Alert ("WebSocket is supported by your Browser! ");
// Let us open a web socket
Var ws = new WebSocket ("ws: // localhost: 9998/echo ");
Ws. onopen = function ()
{
// Web Socket is connected, send data using send ()
Ws. send ("Message to send ");
Alert ("Message is sent ...");
};
Ws. onmessage = function (evt)
{
Var received_msg = evt. data;
Alert ("Message is already ed ...");
};
Ws. onclose = function ()
{
// Websocket is closed.
Alert ("Connection is closed ...");
};
}
Else
{
// The browser doesn' t support WebSocket
Alert ("WebSocket NOT supported by your Browser! ");
}
}
</Script>
</Head>
<Body>
<Div id = "sse">
<A href = "javascript: WebSocketTest ()"> Run WebSocket </a>
</Div>
</Body>
</Html>