WebSocke是一个基于ws协议的技术,它可以实现在客户端和服务器端简历长久连接,
一个典型的websocket了客户端是用户的浏览器,但是这个协议是跨平台的,不受应用限制
创建一个websocket对象
你需要创建一个websocket对象来实现通过websocket协议的通信,对象会自动建立与服务器的连接
1
2
3
4
|
WebSocket WebSocket(
in DOMString url,
in optional DOMString protocols
);
|
url
URL是所要连接的地址,请求这个地址会得到websocket服务器的响应
protocols 可选参数
可以是单个协议,也可以是多个协议组成数组的形式,这些字符串表明其子协议,这样单个服务器可以实现多个websocket子协议(例如,你想让单个服务器基于具体的协议来处理不同的互动类型),如果你没有声明一个协议字符串,默认取空字符串
Connection errors
当尝试连接的时候出现错误,首先一个简单的“error”事件将被发送给websocket对象(从而会调用onerror事件处理器),然后会“closeEvent”事件将被发送给websocket对象(从而会调用onclose事件处理器)来表明连接关闭的原因。
Examples
这个简单的例子创建了一个websocket连接到位于“ws://www.example.com/socketserver”的服务器,通常,第二个参数protocol写为“protocolOne”,这个参数也可以省略。
1
|
var exampleSocket =
new WebSocket(
"ws://www.example.com/socketserver",
"protocolOne");
|
作为返回,exampleSocket.readyState被置为CONNECTING,一旦连接准备好去传输数据,exampleSocket.readyState就被置为OPEN
如果你想建立一个连接,灵活支持你支持的协议,那么可以给第二个参数传入一个协议数组
1
|
var exampleSocket =
new WebSocket(
"ws://www.example.com/socketserver", [
"protocolOne",
"protocolTwo"]);
|
一旦连接被创建,exampleSocket.protocol将告诉你服务器选择的是哪种协议
在上面的示例中ws协议替代http协议,相类似的,wss协议替代https协议
Sending data to the server
ws连接建立好了,你就可以向服务器发送数据,可以使用websocket的send方法来发送数据
1
|
exampleSocket.send(
"Here's some text that the server is urgently awaiting!");
|
你可发送string, blob, ArrayBuffer格式的数据
note: firefox11之前的版本只支持发送字符串
由于创建一个连接是易步的且容易失败,所以不能保证在创建了websocket对象之后立即调用send()方法会成功,我们可以保证可以在onopen事件处理器被定义之后去尝试发送数据
1
2
3
|
exampleSocket.onopen =
function (event) {
exampleSocket.send(
"Here's some text that the server is urgently awaiting!");
};
|
Using JSON to transmit objects
我们可以使用json来方便的传输较复杂的数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
function sendText() {
var msg = {
type:
"message",
text:
document.getElementById(
"text").value,
id: clientID,
date:
Date.now()
};
exampleSocket.send(
JSON.stringify(msg));
document.getElementById(
"text").value =
"";
}
|
Receiving messages from the server
WebSockets 是一个时间驱动的API,当收到一个消息,message事件就会被传递个onmessage函数,来监听收到的数据,你可以这样做
1
2
3
|
exampleSocket.onmessage =
function (event) {
console.log(event.data);
}
|
Receiving and interpreting JSON objects
客户端可能会收到各种类型的数据,例如:
-登陆握手
-消息文本
-用户列表更新
解译收到的数据的代码应该如下:
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
|
exampleSocket.onmessage =
function(event) {
var f =
document.getElementById(
"chatbox").contentDocument;
var text =
"";
var msg =
JSON.parse(event.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);
}
};
|
这里我们使用JSON.parse()把json字符串转化为json对象,然后再按代码执行
文本数据格式
通过websocket连接收到的数据都是utf-8编码的
关闭连接
当你想停止使用websocket连接,可以调用websocket对象的close()方法
安全考虑
websocket不应该在混合环境下使用,这就是,你不能在通过HTTPS 或者 vice-versa加载的页面来简历非安全的websocket连接,事实上,一些浏览器明确的禁止这样做,包括firefox8及后续版本
注:翻译自火狐开发者文档