csdn lidp http://blog.csdn.net/perfectpdl
上一篇文章介绍了 websocket理论,本篇分析websocket协议客户端部分在webkit浏览器引擎上的实现。
websocket api 可以看这里, 协议可以看这里RFC 6455.
webkit上websocket实现代码在WebCore/websockets目录下
一下为webkit WebSocket JavaScript idl 接口的定义(websocket.idl):
module websockets { interface [ Conditional=WEB_SOCKETS, CustomConstructor, EventTarget, NoStaticTables ] WebSocket { readonly attribute DOMString URL; // ready state const unsigned short CONNECTING = 0; const unsigned short OPEN = 1; const unsigned short CLOSED = 2; readonly attribute unsigned short readyState; readonly attribute unsigned long bufferedAmount; // networking attribute EventListener onopen; attribute EventListener onmessage; attribute EventListener onclose; [Custom] boolean send(in DOMString data) raises(DOMException); void close(); // EventTarget interface [Custom] void addEventListener(in DOMString type, in EventListener listener, in boolean useCapture); [Custom] void removeEventListener(in DOMString type, in EventListener listener, in boolean useCapture); boolean dispatchEvent(in Event evt) raises(EventException); }; }
浏览器提供的js接口给web开发人员使用,下面面为客户端建立 WebSocket 连接的实例 JavaScript 代码
var wsServer = 'ws://localhost:8888/Demo'; var websocket = new WebSocket(wsServer); 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) { console.log("Connected to WebSocket server."); } function onClose(evt) { console.log("Disconnected"); } function onMessage(evt) { console.log('Retrieved data from server: ' + evt.data); } function onError(evt) { console.log('Error occured: ' + evt.data); } |