I installed NodeJS on my Ubuntu computer and created the following script ....
var host = 'localhost'
var port = '8080'
var net = require('net');
net.createServer(function (socket) {
socket.write("Echo server\r\n");
socket.on("data", function (data) {
socket.write(data);
});
}).listen(port, host);
console.log('Server running at http://' + host + ':' + port + '/');
Then I run ...
node example.js
... in a terminal that gives me the following ...
Server running at http://localhost:8080/
I created a simple HTML page with the following code ...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'></script>
<script>
$(document).ready(function(){
if(!("WebSocket" in window)) {
alert("Sorry, the build of your browser does not support WebSockets.");
return;
}
ws = new WebSocket("ws://localhost:8080/");
ws.onclose = function() {
alert("socket closed");
};
ws.onopen = function() {
alert("socked opened");
};
ws.onmessage = function() {
alert("message received");
};
$( 'button' ).click( function() {
ws.send( "testing" );
});
setInterval( function() {
$( 'p.readyState' ).text( ws.readyState );
}, 1000 );
});
</script>
</head>
<body>
<button type="button">Click Me!</button>
<p class="readyState"></p>
</body>
</html>
But when I look at the page, I get no feedback, and readyState is always 0. If I stop the server while the page is still open, I get a warning about closing the socket.
I tested this script in Chrome (8.0.552.215), Firefox 4 (Beta 7) and Opera 11 (beta).
Does anyone have any suggestions?
Thank!
source
share