WebSocket
2011-11-20 08:01 by 【当耐特砖家】, 3386 阅读, 9 评论, 收藏, 编辑一.简介
WebSocket 是HTML5一种新的协议。它是实现了浏览器与服务器的双向通讯。
在 WebSocket API 中,浏览器和服务器只需要要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
现在,很多网站为了实现即时通讯,所用的技术都是轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP request,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP request 的header是非常长的,里面包含的数据可能只是一个很小的值,这样会占用很多的带宽和服务器资源。
而比较新的技术去做轮询的效果是Comet,使用了AJAX。但这种技术虽然可达到双向通信,但依然需要发出请求,而且在Comet中,普遍采用了长链接,这也会大量消耗服务器带宽和资源。
面对这种状况,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽并达到实时通讯。
二.构建一个WebSocket client App
在使用webSocket之前,我们做浏览器支持判断:
1
2
3
4
5
6
|
var
WebSocketsExist =
true
;
try
{
}
catch
(ex) {
WebSocketsExist =
false
;
}
|
在创建websocket对象之前,我们先来看看他的两个构造函数
1
2
3
|
WebSocket WebSocket( in DOMString url, in optional DOMString protocols);
WebSocket WebSocket( in DOMString url, in optional DOMString[] protocols);
|
在javascript,我们这个来创建webSocket对象:
1
2
|
var
mySocket =
new
WebSocket(
"http://www.example.com/socketserver"
, [
"protocol1"
,
"protocol2"
]);
|
发送消息:
1
|
mySocket.send(
"Test Message!"
);
|
接受消息:
1
2
3
|
mySocket.onmessage =
function
(e) {
//e.data
}
|
当然服务器与客户端可以用JSON格式通信,例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
function
sendText() {
var
msg = {
type:
"message"
,
text: document.getElementById(
"text"
).value,
id: clientID,
date: Date.now()
};
mySocket.send(JSON.stringify(msg));
document.getElementById(
"text"
).value =
""
;
}
connection.onmessage =
function
(evt) {
var
f = document.getElementById(
"chatbox"
).contentDocument;
var
text =
""
;
var
msg = JSON.parse(evt.data);
var
time =
new
Date(msg.date);
var
timeStr = time.toLocaleTimeString();
switch
(msg.type) {
case
"id"
:
clientID = msg.id;
setUsername();
break
;
case
"username"
:
text =
"<b>User <em>"
+ msg.name +
"</em> signed in at "
+ timeStr +
"</b><br>"
;
break
;
case
"message"
:
text =
"("
+ timeStr +
") <b>"
+ msg.name +
"</b>: "
+ msg.text +
"<br>"
;
break
;
case
"rejectusername"
:
text =
"<b>Your username has been set to <em>"
+ msg.name +
"</em> because the name you chose is in use.</b><br>"
break
;
case
"userlist"
:
var
ul =
""
;
for
(i = 0; i < msg.users.length; i++) {
ul += msg.users[i] +
"<br>"
;
}
document.getElementById(
"userlistbox"
).innerHTML = ul;
break
;
}
if
(text.length) {
f.write(text);
document.getElementById(
"chatbox"
).contentWindow.scrollByPages(1);
}
};
|
事件:
1
2
3
4
|
ws.onopen = WSonOpen;
ws.onmessage = WSonMessage;
ws.onclose = WSonClose;
ws.onerror = WSonError;
|
状态:
1
2
3
4
5
|
// Web Socket connecting
ws.readyState == 0
// Web Socket connected
ws.readyState == 1
// Web Socket connected
|
关闭连接:
1
|
mySocket.close();
|
三.服务器
在服务器方面,网上都有不同对websocket支持的服务器:
- php - http://code.google.com/p/phpwebsocket/
- jetty - http://jetty.codehaus.org/jetty/ (版本7才开始支持websocket)
- netty - http://www.jboss.org/netty
- ruby - http://github.com/gimite/web-socket-ruby
- Kaazing - http://www.kaazing.org/confluence/display/KAAZING/Home