//==========websocket(function($) { $.websocket = function(options) { var defaults = { domain: top.location.hostname, port:3398, protocol:"" }; var opts = $.extend(defaults,options); var szServer = "ws://" + opts.domain + ":" + opts.port +
//==========websocket (function($) { $.websocket = function(options) { var defaults = { domain: top.location.hostname, port:3398, protocol:"" }; var opts = $.extend(defaults,options); var szServer = "ws://" + opts.domain + ":" + opts.port + "/" + opts.protocol; var socket = null; var bOpen = false; var t1 = 0; var t2 = 0; var messageevent = { onInit:function(){ if(!("WebSocket" in window) && !("MozWebSocket" in window)){ return false; } if(("MozWebSocket" in window)){ socket = new MozWebSocket(szServer); }else{ socket = new WebSocket(szServer); } if(opts.onInit){ opts.onInit(); } }, onOpen:function(event){ bOpen = true; if(opts.onOpen){ opts.onOpen(event); } }, onSend:function(msg){ t1 = new Date().getTime(); if(opts.onSend){ opts.onSend(msg); } socket.send(msg); }, onMessage:function(msg){ t2 = new Date().getTime(); if(opts.onMessage){ opts.onMessage(msg.data,t2 - t1); } }, onError:function(event){ if(opts.onError){ opts.onError(event); } }, onClose:function(event){ if(opts.onclose){ opts.onclose(event); } if(socket.close() != null){ socket = null; } } } messageevent.onInit(); socket.onopen = messageevent.onOpen; socket.onmessage = messageevent.onMessage; socket.onerror = messageevent.onError; socket.onclose = messageevent.onClose; this.send = function(pData){ if(bOpen == false){ return false; } messageevent.onSend(pData); return true; } this.close = function(){ messageevent.onClose(); } return this; }; })(jQuery); ---------使用示例------------ //=========启动一个websocket var Socket1 = $.websocket({ domain:"www.qhnovel.com", //这是与服务器的域名或IP port:8080, //这是服务器端口号 protocol:"text", //这东西可有可无,组合起来就是 ws://www.qhnovel.com:8080/test onOpen:function(event){ alert("已经与服务端握手,onOpen可省略不写"); }, onError:function(event){ alert("发生了错误,onError可省略不写"); }, onSend:function(msg){ alert("发送数据额外的代码,可省略不写"); }, onMessage:function(result,nTime){ alert("从服务端收到的数据:" + result); alert("最近一次发送数据到现在接收一共使用时间:" + nTime); } }); //=========发送数据方式 Socket1.send("要发送的数据"); //=========关闭连接 Socket1.close(); Socket.bOpen == false 时候没有连接到服务端