TCP/IP protocol
. TCP/IP protocol significant is less when compared to HTTP protocol because TCP/IP layer is present below HTTP layer.
Schemes for the HTTP protocol are http://
or http://
and for WebSockets ws://
or wss://
To set the WebSocket connection user need to use the WebSocket () constructor.
[html]
var Socket = new WebSocket
[/html]
The argument of the WebSocket() is used as a URL for the host connections and port numbers. The protocol ws:// or wss:// is used for this connections.
[html]
<script>
// Create a WebSocket Connection
var socket= new WebSocket("ws://www.example.com/webSocketserver.php");
</script>
[/html]
In order get the current state use the readyState attribute which can assume 4 values as shown below.
Value | Numeric valiue | Description |
---|---|---|
CONNECTING | 0 | Used to openning a connction |
OPEN | 1 | Used to a connction opened |
CLOSING | 2 | Used to openning a connction |
CLOSED | 3 | Used to a connction closed |
send()
method.
[html]
Socket.send(“some message ! ”);
[/html]
[html]
<script>
// Create a WebSocket Connection
var socket= new WebSocket("ws://www.example.com/webSocketserver.php");
//Send your message using method send().
socket.send("Message");
/*WebSockets accept only plain text, hence
complex data can be serialized using JSON strings.*/
var biodata = {
Name: "Harry Potter",
School: "Hogwarts ",
Id: "Gryffindor0123"
}
socket.send(JSON.stringify(biodata));
</script>
[/html]
The four types of events are used to handle the WebSockets when they get connected.
Event Handler | Description |
---|---|
onopen | Is get into action when the WebSocket connection is established. |
onclose | Is get into action when the WebSocket connection is closed |
onerror | Is get into action when Error occured |
onmessage | Is get into action when server send a message to the client |
close()
method the code is as shown below.
[html]
<script>
// Create a WebSocket Connection
var socket= new WebSocket("ws://www.example.com/webSocketserver.php");
// Web Socket is now connected.
socket.close();
</script>
[/html]