本文主要是介绍Webscoket的使用以及优化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
最近项目中用到了webscoket,直接把代码放到这里,有问题互相讨论
var ws = null;
var url = null;
var transports = [];
var timestamp = Date.parse(new Date());
timestamp = timestamp / 1000; function setConnected(connected) { document.getElementById('connect').disabled = connected; document.getElementById('disconnect').disabled = !connected; document.getElementById('echo').disabled = !connected;
} function connect() {//ws = new SockJS("http://127.0.0.1:8080/sym_cop/s1/sockjs/websck?k=8377bf3e-af81-4eb4-816e-b7e05ef3f774");if ('WebSocket' in window) {var ipUrl = window.location.host;ipUrl = ipUrl.split(':')[0];ws= new WebSocket("ws://"+ ipUrl +":8020/s1/websck?k="+ $.cookie('k')); // console.log("http://127.0.0.1:8080/sym_cop/s1/websck"); }ws.onopen = function () { // ws.send(message); }; ws.onmessage = function (event) { log(event.data); }; ws.onclose = function (event) { log('connection closed.'); // log(event);var a=Date.parse(new Date());a=a/1000;if(a-timestamp>10){ connect();}else{setTimeout(function(){connect();},10000)}timestamp = Date.parse(new Date());timestamp = timestamp / 1000; };} function disconnect() { if (ws != null) { ws.close(); ws = null; } setConnected(false);
}
setInterval(function(){if(ws){ws.send('heart');}
},30000)
function echo() { if (ws != null) { var message = document.getElementById('message').value; //log('Sent: ' + message); ws.send(message); } else { alert('connection not established, please connect.'); }
} function updateUrl(urlPath) { if (urlPath.indexOf('sockjs') != -1) { url = urlPath; document.getElementById('sockJsTransportSelect').style.visibility = 'visible'; } else { if (window.location.protocol == 'http:') {url = 'ws://' + window.location.host + urlPath; } else { url = 'wss://' + window.location.host + urlPath; } document.getElementById('sockJsTransportSelect').style.visibility = 'hidden'; }
} function updateTransport(transport) { // alert(transport); transports = (transport == 'all') ? [] : [transport];
} function log(message) {if(message == 'heart'){return}if(message == 'connection closed.'){}else if(message == "Server:connected OK!"){setTimeout(function(){getPouple();},300)}else{setTimeout(function(){getPouple();},300)}}
这篇关于Webscoket的使用以及优化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!