最近项目中用到了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() {
if ('WebSocket' in window) {
var ipUrl = window.location.host;
ipUrl = ipUrl.split(':')[0];
ws= new WebSocket("ws://"+ ipUrl +":8020/s1/websck?k="+ $.cookie('k'));
}
ws.onopen = function () {
};
ws.onmessage = function (event) {
log(event.data);
};
ws.onclose = function (event) {
log('connection closed.');
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;
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) {
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)
}
}