经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JSJS库框架 » jQuery » 查看文章
基于HTTP的长轮询简单实现
来源:cnblogs  作者:冰湖一角  时间:2018/9/25 20:07:39  对本文有异议

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

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

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

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

长轮询机制如下图所示:

web客户端代码如下:

  1. //向后台长轮询消息
  2. function longPolling(){
  3. $.ajax({
  4. async : true,//异步
  5. url : 'longPollingAction!getMessages.action',
  6. type : 'post',
  7. dataType : 'json',
  8. data :{},
  9. timeout : 30000,//超时时间设定30秒
  10. error : function(xhr, textStatus, thrownError) {
  11. longPolling();//发生异常错误后再次发起请求
  12. },
  13. success : function(response) {
  14. message = response.data.message;
  15. if(message!="timeout"){
  16. broadcast();//收到消息后发布消息
  17. }
  18. longPolling();
  19. }
  20. });
  21. }

web服务器端代码如下:

  1. public class LongPollingAction extends BaseAction {
  2. private static final long serialVersionUID = 1L;
  3. private LongPollingService longPollingService;
  4. private static final long TIMEOUT = 20000;// 超时时间设置为20秒
  5.  
  6. public String getMessages() {
  7. long requestTime = System.currentTimeMillis();
  8. result.clear();
  9. try {
  10. String msg = null;
  11. while ((System.currentTimeMillis() - requestTime) < TIMEOUT) {
  12. msg = longPollingService.getMessages();
  13. if (msg != null) {
  14. break; // 跳出循环,返回数据
  15. } else {
  16. Thread.sleep(1000);// 休眠1秒
  17. }
  18. }
  19. if (msg == null) {
  20. result.addData("message", "timeout");// 超时
  21. } else {
  22. result.addData("message", msg);
  23. }
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. return SUCCESS;
  28. }
  29. public LongPollingService getLongPollingService() {
  30. return longPollingService;
  31. }
  32. public void setLongPollingService(LongPollingService longPollingService) {
  33. this.longPollingService = longPollingService;
  34. }
  35. }

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号