1.1 检测浏览器支持的情况
if (window.WebSocket)
支持
else
不支持
1.2 API的基本用法
url = “ws//loaclhost:8888:/echo”;
w = new WebSocket(url);
或
w = new WebSocket(url, ["proto1", "proto2"];
使用已知的协议, 该协议被服务端和客户端所都接受, 比如XMPP, RFB等,用来开启通向公告WebSocket服务的大门。
1.2.1 添加监听事件
w.onopen = function () {
}
w.onmessage = function(e) {
}
w.onclose = function(e) {
}
w.onerror = function(e) {
}
1.2.2 发送消息
w.send("Message");
其中w.buffferedAmount属性,表示已在WebSocket发送但未写入网络的字节数。
WebSocket能发字符串,也能发送二进制的数据。
websocket.html
<!DOCTYPE html >
<html>
<head>
<meta
charset
=
"UTF-8"
>
<title>
WebSocket
</title>
</head>
<body>
<div>
<input
type
=
"text"
id
=
"inputMessage"
value
=
"Hello, Web Socket"
></input>
<input
type
=
"button"
id
=
"sendBtn"
value
=
"send"
></input>
</div>
</body>
<script
type
=
"text/javascript"
src
=
"./jquery-2.1.1.js"
></script>
<script
type
=
"text/javascript"
src
=
"./websocket.js"
></script>
</html>
websocket.js
var
log =
function
(s) {
log.buffer.push(s);
};
log.buffer = [];
var
url =
"ws://localhost:8080/echo"
;
var
w =
new
WebSocket(url);
//新建 websocket连接
w.onpen =
function
() {
//websocket连接上会被调用
w.send(
"12312"
);
};
w.onmessage =
function
(e) {
//收到消息被调用
log(e.data);
};
w.onclose =
function
() {
//连接被关闭调用
log(
"closed"
);
};
$(
function
() {
if
(!window.WebSocket) {
//检测浏览器是否支持。
alert(
"亲,很抱歉,您的浏览器不支持WebSocket"
);
}
log(log.buffer.join(
"\n"
));
$(
"#sendBtn"
).click(
function
() {
w.send(
"1231"
);
w.send($(
"#inputMessage"
).val());
});
});