The API exposed
One of the goals of the W3C was the simplicity and ease of use of WebSocket. The API exposed are very simple. The entire management of communication flow is delegated to an object WebSocket that has methods for sending and event-oriented listeners to receive messages. As we will see shortly, the API is very similar to those used in the previous article concerning WebWorkers. To create a WebSocket the only parameter required is the URL where this must be to:
var = new webSocket WebSocket ("ws://www.websocket.org");
Once you create the object we have two methods for sending information and for closing the communication channel:
webSocket.send ("Hello world");
webSocket.close ()
Instead of interacting with the messages received from the server and the state change can use the same WebSocket listeners:
Code:
webSocket.onopen = function (event) {
console.log ("Connection opened");
}
webSocket.onmessage = function (event) {
console.log ("Server says" + event.data);
}
webSocket.onerror = function (event) {
console.log ("Error!!");
}
webSocket.onclose = function (event) {
console.log ("Connection closed");
}
Bookmarks