分类: 系统运维
2012-07-29 15:47:04
什么是WebSocket?
The WebSocket specification—developed as part of the HTML5 initiative—introduced the WebSocket JavaScript interface, which defines a full-duplex single socket connection over which messages can be sent between client and server. The WebSocket standard simplifies much of the complexity around bi-directional web communication and connection management.
WebSocket represents the next evolutionary step in web communication compared to Comet and Ajax. However, each technology has its own unique capabilities. Learn how these technologies vary so you can make the right choice.
规范-——成熟的HTML5技术创新——WebSocket javascript接口是什么?它是一个全双工的socket连接,通过这个socket连接我们可以在客户端和服务端之间传递信息。WebSocket标准大大简化了网络通讯双方的复杂性和连接管理。
和长连接和Ajax相比,WebSocket 代表着进入网络通讯下一次革命。但是每一项技术都有它自身独有的能力。学会这些技术变革,你就可以选择正确的技术去完成你的工作。
Creating your own test
创建你自己的测试
Using a text editor, copy the following code and save it as websocket.html somewhere on your hard drive. Then simply open it in a browser. The page will automatically connect, send a message, display the response, and close the connection.
把下面的代码复制到编辑器里,并且保存为websocket.html。然后用浏览器打开它。这个页面会自动连接,发送一个消息,显示响应内容,最后关闭(ps:我自己试了chrome11下是可以的,firefox4和IE9不行)
var wsUri = "ws://echo.websocket.org/";
var output;
//初始化
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
//实例化WebSocket
websocket = new WebSocket(wsUri);
//注入回调函数
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) }; }
//连接打开
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket rocks"); }
//连接关闭回调函数
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
//收到消息回调函数
function onMessage(evt) {
writeToScreen('RESPONSE: ' + evt.data+''); websocket.close();
}
//出错回调函数
function onError(evt) {
writeToScreen('ERROR: ' + evt.data);
}
//发是信息到服务端
function doSend(message) {
writeToScreen("SENT: " + message);
websocket.send(message);
}
//把内容输出到页面的output div里
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
//开始执行
window.addEventListener("load", init, false);
WebSocket Test