web客户端与服务器之间基于ajax(http)的常用通信方式,分为短连接与长轮询。

短连接:客户端和服务器每进行一次http操作,就建立一次连接,任务结束就中断连接。

在长轮询机制中,客户端像传统轮询一样从服务器请求数据。然而,如果服务器没有可以立即返回给客户端的数据,则不会立刻返回一个空结果,

而是保持这个请求等待数据到来(或者恰当的超时:小于ajax的超时时间),之后将数据作为结果返回给客户端。

长轮询机制如下图所示:

9d2ef45eeb7c1d7f22d5d1ec78c43285.png

web客户端代码如下:

//向后台长轮询消息

function longpolling(){

$.ajax({

async : true,//异步

url : 'longpollingaction!getmessages.action',

type : 'post',

datatype : 'json',

data :{},

timeout : 30000,//超时时间设定30秒

error : function(xhr, textstatus, thrownerror) {

longpolling();//发生异常错误后再次发起请求

},

success : function(response) {

message = response.data.message;

if(message!="timeout"){

broadcast();//收到消息后发布消息

}

longpolling();

}

});

}

web服务器端代码如下:

public class longpollingaction extends baseaction {

private static final long serialversionuid = 1l;

private longpollingservice longpollingservice;

private static final long timeout = 20000;// 超时时间设置为20秒

public string getmessages() {

long requesttime = system.currenttimemillis();

result.clear();

try {

string msg = null;

while ((system.currenttimemillis() - requesttime) < timeout) {

msg = longpollingservice.getmessages();

if (msg != null) {

break; // 跳出循环,返回数据

} else {

thread.sleep(1000);// 休眠1秒

}

}

if (msg == null) {

result.adddata("message", "timeout");// 超时

} else {

result.adddata("message", msg);

}

} catch (exception e) {

e.printstacktrace();

}

return success;

}

public longpollingservice getlongpollingservice() {

return longpollingservice;

}

public void setlongpollingservice(longpollingservice longpollingservice) {

this.longpollingservice = longpollingservice;

}

}

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐