var _WSServerAddress = "ws://localhost:6003";

function WSClient() {
  this.ws = null;
  this.isDebug = true;
  var that = this;

  this.connect = function() {
    if(!window.WebSocket) {
      alert('当前浏览器不支持WebSocket！');
      return;
    }
    this.ws = null;
    this.ws = new WebSocket(_WSServerAddress);

    this.ws.onopen = function(e){
      console.log("连接WebSocket服务器成功。");

      //登录服务器
      that.send(taskMsgAuthObj.getWSLoginData());
    };
    this.ws.onclose = function(e){
      console.log("WebSocket服务器已关闭。");
      that.ws = null;
    };
    this.ws.onerror = function(){
      console.log("WebSocket连接出错。");
      that.ws = null;
    };
    // 接收服务器的消息
    this.ws.onmessage = function(e){
      if(that.isDebug) console.log('收到消息：'+e.data);
      var msg = JSON.parse(e.data);
      if(msg.type=="loginRet") {
        //登录后马上接收离线消息
        that.receive(0);
      } else if(msg.type=="newMsg") {
        that.receive(0);
      } else if(msg.type=="getNewMsgRet") {
        //如果没有消息了就停止接收
        if(!msg.msg) {
          return;
        }
        that.process(msg.msg);
        //继续接收下一条消息
        that.receive(msg.msg.id);
      } else if(msg.type=="error") {
        console.log(msg.message);
      }
    };
  };

  this.send = function(msg) {
    if(!this.ws) return;
    var msgStr = msg;
    if(typeof msg != String) {
      msgStr = JSON.stringify(msg);
    }
    if(that.isDebug) console.log('发送消息：'+msgStr);
    try {
      this.ws.send(msgStr);
    } catch(err) {
      console.log('消息发送失败，错误描述：'+err.message);
    }
  };

  this.receive = function(msgId) {
    var msg = {
      service: 'receive',
      args: [msgId]
    };
    this.send(msg);
  };

  this.process = function(msg) {
    console.log(msg);
  };
};

$(function() {
  var wsClient = new WSClient();
  wsClient.connect();
});