function WebSocketConnect(url) { var ws = null; /** * state explanation:DISCONNECT: 4 、CLOSED: 3 、CLOSING: 2 、CONNECTING: 0 、OPEN: 1 */ var msgJson = { evt:null, state:null }; WebSocketConnect.prototype.connect = function(callback) { if ('WebSocket' in window) { ws = new WebSocket(url); } else if ('MozWebSocket' in window) { ws = new MozWebSocket(url); } else { msgJson.state = 4; callback(msgJson); } WebSocketConnect.prototype.close = function(){ ws.close(); }; /** * connect close */ ws.onclose = function(evt) { msgJson.evt = evt; msgJson.state = ws.readyState; callback(msgJson); }; /** * connect error */ ws.onerror = function(evt) { msgJson.evt = evt; msgJson.state = ws.readyState; callback(msgJson); }; /** * connect open */ ws.onopen = function(evt) { msgJson.evt = evt; msgJson.state = ws.readyState; callback(msgJson); }; /** * connect return message */ ws.onmessage = function(evt){ msgJson.evt = evt; msgJson.state = ws.readyState; callback(msgJson); }; }; }
調用實例:html
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>test</title> <script src="./WebSocketConnect.js"></script> </head> <body> <div id="label1"></div> <div><canvas id="image123"></canvas></div> <div><canvas id="image122"></canvas></div> <script> var ws = new WebSocketConnect("ws://192.168.1.239/push"); var imageObj = new Image(); var canvas=document.getElementById('image123'); var canvas1=document.getElementById('image122'); var ctx=canvas.getContext('2d'); var ctx1=canvas1.getContext('2d'); function callBack(data){ try{ var state = data.state; var evt = data.evt; var obj = eval("("+evt.data+")"); imageObj.src = "http://192.168.1.239/"+obj.FrameIndex+".jpg?r="+Math.random(); imageObj.onload = function(){ canvas.width = imageObj.width; canvas.height = imageObj.height; ctx.drawImage(imageObj,0,0); canvas1.width = imageObj.width; canvas1.height = imageObj.height; ctx1.drawImage(imageObj,0,0); }; }catch(e){ } } ws.connect(callBack); </script> </body> </html>