var WebSocketServer = require('ws').Server;
var socket = new WebSocket('ws://www.websocket-testing.com:9000/server', 'subprotocol');
socket.onopen = function(e) {
console.log('websocket connection has established');
}
//send message to websocket server
socket.send('hello, server');

//receive message from websocket server
socket.onmessage = function(e){
//obtain the message from server
var message = e.data;

//do something
}

//cut off the connection
socket.close();

socket.onclose = function(e){
//do something
}
//监听到失败后重新连接
socket.onclose = function() {
setTimeout(function() {
//reconnect operation
}, 100000);
}

一次任务然后就关闭了。


var w;

function startWorker()
{
if(typeof(Worker)!=="undefined")
{
if(typeof(w)=="undefined")
{
w=new Worker("/example/html5/demo_workers.js");
}
w.onmessage = function (event) {
document.getElementById("result").innerHTML=event.data;
};
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";
}
}

function stopWorker()
{
w.terminate();
}



Server-Sent 事件 - 单向消息传递

Server-Sent 事件指的是网页自动获取来自服务器的更新。


var source=new EventSource("demo_sse.php");
source.onmessage=function(event)
{
document.getElementById("result").innerHTML+=event.data + "<br />";
};