欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring MVC4.1服務(wù)器端推送實(shí)現(xiàn)過(guò)程解析

 更新時(shí)間:2019年11月29日 09:51:18   投稿:yaominghui  
這篇文章主要介紹了Spring MVC4.1服務(wù)器端推送實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

這篇文章主要介紹了Spring MVC4.1服務(wù)器端推送實(shí)現(xiàn)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

服務(wù)器端推送

  • SSE(server send event)是一種服務(wù)器端向?yàn)g覽器推送消息的技術(shù),而不是我們常規(guī)的瀏覽器像server請(qǐng)求然后響應(yīng);
  • 當(dāng)我們需要使用server向?yàn)g覽器主動(dòng)推送數(shù)據(jù)的時(shí)候,請(qǐng)考慮使用該項(xiàng)技術(shù),而不是考慮具有雙向通訊功能的websocket;
  • 以前我們用ajax輪詢server也能實(shí)現(xiàn),服務(wù)器負(fù)擔(dān)大;
  • sse原理是向server請(qǐng)求一次后,server會(huì)掛住請(qǐng)求不放(此時(shí)瀏覽器里請(qǐng)求狀態(tài)是pending),等有數(shù)據(jù)后才返回給瀏覽器,然后再發(fā)起下一次請(qǐng)求,以此類(lèi)推;
  • 所有主流瀏覽器均支持服務(wù)器發(fā)送事件,除了 Internet Explorer(6,7,8,9);

示例

服務(wù)器推送控制器

package com.wisely.web;

import java.util.Random;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SSEController {
  //注意produces="text/event-stream"
  @RequestMapping(value="/push",produces="text/event-stream")
  public @ResponseBody String push(){
     Random r = new Random();
     try {
         Thread.sleep(5000);
     } catch (InterruptedException e) {
         e.printStackTrace();
     }
     return "data:Testing 1,2,3" + r.nextInt() +"\n\n";
  }
}

頁(yè)面代碼

<div id="msg_from_server"></div>
<script type="text/javascript" src="<c:url value="/js/jquery.js" />"></script>
<script type="text/javascript">
if (!!window.EventSource) {
    var source = new EventSource('push'); //為http://localhost:8080/testSpringMVC/push
    s='';
    source.addEventListener('message', function(e) {

      s+=e.data+"<br/>"
      $("#msg_from_server").html(s);

    });

    source.addEventListener('open', function(e) {
      console.log("連接打開(kāi).");
    }, false);

    source.addEventListener('error', function(e) {
      if (e.readyState == EventSource.CLOSED) {
        console.log("連接關(guān)閉");
      } else {
        console.log(e.readyState);  
      }
    }, false);
  } else {
      console.log("沒(méi)有sse");
  }
</script>

效果

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論