WebSocket protocol is a new network protocol based on TCP. It implements full-duplex communication between the browser and the server - allowing the server to actively send information to the client.
The WebSocket protocol supports full- duplex communication between a client ( running untrusted code in a controlled environment ) and a remote host (opting in to the code's communication) . The security model used for this is the raw-based security model commonly used by web browsers. The protocol consists of an open handshake followed by message frames on the TCP layer. The goal of this technology is to provide a communication mechanism for browser-based applications that require two-way communication with the server (the server cannot rely on opening multiple HTTP connections (eg, using XMLHttpRequest or <iframe> and long polling)) .
Implementation principle
Handshake Protocol Example
Upgrade: websocket
Sec-WebSocket-Key: xqBt3ImNzJbYqRINxEFlkg==
Origin: http://server address
Sec-WebSocket-Version: 13
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: K7DJLdLooIwIG/MOpvWFB3y3FE8=
HTML5 Web Socket API
创建对象
1
|
var
ws =
new
WebSocket(url,name);
|
发送文本消息
1
|
ws.send(msg);
|
接收消息
1
|
ws.onmessage = (
function
(){...})();
|
错误处理
1
|
ws.onerror = (
function
(){...})();
|
关闭连接
1
|
ws.close();
|