Receive our weekly advanced programming tips for FREE
21.April
How to use the HTML5 WebSocket
0
| 0 votes
Autor: bookkeeper
Chapter: JavaScript

Since HTML5 sockets will be avaiable as WebSocket. Finally we can write applications with real sockets!

 And it's very easy to use:

First create a WebSocket instance:

var wb = new WebSocket("ws://www.programmersbook.com");

After install the callbacks:

wb.onopen = function(evt) { alert("Connection open ..."); };
wb.onmessage = function(evt) { alert( "Received Message: "  +  evt.data); };
wb.onclose = function(evt) { alert("Connection closed."); };

Send some data when onopen is ready otherwise you get an INVALID_STATE_ERR exception:

wb.send("Hello programmers!");

When you finished close the socket:

myWebSocket.close();

It very interesting to use it in combination with Web Workers alias Threads!

Have Fun!