1.html5的SSE (server-sent
event)
A server-sent event is when a web page automatically gets
updates from a server.
This was also possible before, but the web page would have
to ask if any updates were available. With server-sent events, the updates
come automatically.
使用之前,先用
if(typeof (EventSource) !== 'undefined')
to check if the browser supports this
Object.
varsource=newEventSource('demo_sse.php');
source.onmessage=function(event){
console.log(event.data);}
Example explained:
Create a new EventSource object, and specify the URL of the
page sending the updates (in this example "demo_sse.php")
Each time an update is received, the onmessage event
occurs
more functions:
onmessage
onerror
onopen // when the connection is
linked
2.WebSocket
其实webSocket
是基于HTML5的一种新的文件传输协议,不同于http,它可以直接获取服务器端update回来的数据
首先我们来看个典型的Websocket握手(借用Wikipedia的。。)
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
Upgrade: websocket
Connection: Upgrade
这个就是Websocket的核心了,告诉Apache、Nginx等服务器:注意啦,窝发起的是Websocket协议,快点帮我找到对应的助理处理~不是那个老土的HTTP。
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
然后服务器会返回下列东西,表示已经接受到请求, 成功建立Websocket啦!
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
至此,HTTP已经完成它所有工作了,接下来就是完全按照Websocket协议进行了。
写法:
if('webSocket'inwindow)
{ varws=newWebSocket(URL);
ws.onopen=function()
{ ws.send(); }
ws.onmessage=function(event)
{ console.log(event.data); }
}
//onmessage onopen onclose onerror
Reference:
1、http://www.w3schools.com/html/html5_serversentevents.asp
2、https://www.zhihu.com/question/20215561/answer/40316953
3、https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket
其实就我个人理解:websocket ,SSE,web worker
这三个很像,实际上原理都一样,不过是websocket 跟SSE是针对
server,而webworker是为了在后台跑JS。
他们都是通过new一个Obejct来制定绑定的JS文件或者服务器,然后onmessage 监听
传回来的数据。方法有所不同,server块的有四种,而webworker
关闭的方式是.terminate()