websocket demo 说明

网站:

http://html5demos.com/web-socket 

客户端源码: 

https://github.com/remy/html5demos/blob/master/demos/web-socket.html 

检测是否支持websocket

if (window.WebSocket === undefined) {
  state.innerHTML = 'Sockets not supported';
  state.className = 'fail';

} 

开启websocket

conn = {} 

  if (conn.readyState === undefined || conn.readyState > 1) {

 

//新建一个连接 

    conn = new WebSocket('ws://node.remysharp.com:8001');

 

//连接成功的状态事件
    conn.onopen = function () {
      state.className = 'success';
      state.innerHTML = 'Socket open';
    };

//收到信息回调函数 

    conn.onmessage = function (event) {
      var message = JSON.parse(event.data);
      if (typeof message == 'string') {
        log.innerHTML = '<li class="them">' + message.replace(/[<>&]/g, function (m) { return entities[m]; }) + '</li>' + log.innerHTML;
      } else {
        connected.innerHTML = message;
      }
    };
    

//连接关闭回调函数 

    conn.onclose = function (event) {
      state.className = 'fail';
      state.innerHTML = 'Socket closed';
    }; 

  } 

发送信息:

    if (conn.readyState === 1) {

      conn.send(JSON.stringify(chat.value)); } 

服务端代码解析 省略了,懒得解析,写的非常一般,还不如用java实现算了:


http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 

web socket 最新76协议。

原文地址:https://www.cnblogs.com/zc22/p/1959936.html