亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
在JavaScript中啟用SSE
首頁 web前端 H5教程 如何在HTML5中使用服務(wù)器量事件(SSE)?

如何在HTML5中使用服務(wù)器量事件(SSE)?

Sep 21, 2025 am 06:11 AM
html5 sse

SSE通過HTTP啟用實時的單向服務(wù)器對客戶更新;使用JavaScript中的EventSource連接,使用OnMessage處理消息,將服務(wù)器響應(yīng)類型設(shè)置為文本/事件流,格式數(shù)據(jù),帶有“數(shù)據(jù):”和“ \ n \ n”的格式數(shù)據(jù),并可選地包含用于重新連接的事件ID。

如何在HTML5中使用服務(wù)器量事件(SSE)?

HTML5中的服務(wù)器范圍事件(SSE)允許網(wǎng)頁從服務(wù)器中獲取自動更新而無需進(jìn)行輪詢。當(dāng)您需要實時數(shù)據(jù)(例如實時供稿,通知或股票)等實時數(shù)據(jù)時,這很有用。與WebSocket不同,SSE是單向的 - DATA從服務(wù)器到客戶端的流動 - 它可以通過標(biāo)準(zhǔn)HTTP進(jìn)行工作。

在JavaScript中啟用SSE

要使用SSE,請在JavaScript代碼中創(chuàng)建Eventsource對象。傳遞發(fā)送事件數(shù)據(jù)的服務(wù)器端點(diǎn)的URL。

    使用服務(wù)器URL
  • 使用onMessage處理程序的傳入消息
  • 創(chuàng)建新的Eventsource實例,
  • 可選地處理錯誤

例子:

 <code>if (typeof EventSource !== "undefined") { const source = new EventSource("/sse-updates"); source.onmessage = function(event) { document.getElementById("result").innerHTML = event.data "<br>"; }; source.onerror = function() { console.log("EventSource failed."); }; } else { document.getElementById("result").innerHTML = "SSE not supported"; }</code>設(shè)置服務(wù)器響應(yīng)<code>if (typeof EventSource !== "undefined") { const source = new EventSource("/sse-updates"); source.onmessage = function(event) { document.getElementById("result").innerHTML = event.data "<br>"; }; source.onerror = function() { console.log("EventSource failed."); }; } else { document.getElementById("result").innerHTML = "SSE not supported"; }</code><h3></h3><p>服務(wù)器必須使用特定格式發(fā)送數(shù)據(jù)并設(shè)置正確的MIME類型:<strong>文本/事件流</strong>。</p><font color="#000000"><ul>
<li>響應(yīng)內(nèi)容類型應(yīng)為<strong>文本/事件流</strong>
</li>
<li>數(shù)據(jù)行以<strong>數(shù)據(jù)開頭:</strong>隨后是消息</li>
<li>結(jié)束每個消息,每個消息都有兩個newline字符(\ n \ n)</li>
<li>可選:inclage <strong>ID:</strong>用于重新連接跟蹤或<strong>重試:</strong>用于重試間隔</li>
</ul></font><p>示例服務(wù)器響應(yīng)(node.js/express):</p><pre class="brush:php;toolbar:false"> <code>app.get('/sse-updates', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); setInterval(() => { res.write(`data: ${new Date().toISOString()}\n\n`); }, 1000); });</code>處理連接狀態(tài)并重新連接<code>app.get('/sse-updates', (req, res) => { res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' }); setInterval(() => { res.write(`data: ${new Date().toISOString()}\n\n`); }, 1000); });</code><h3></h3><p> SSE自動嘗試重新連接連接是否下降。瀏覽器使用最后一個看到的事件ID恢復(fù)其關(guān)閉的位置 - 如果服務(wù)器支持它。</p><font color="#000000"><ul>
<li>發(fā)送一個<strong>ID:</strong>每個事件的字段,以便服務(wù)器可以跟蹤位置</li>
<li>使用<strong>source.close()</strong>手動停止偵聽</li>
<li>監(jiān)視器readystate:0(連接),1(open),2(閉合)</li>
</ul></font><p>帶有事件ID的示例:</p><pre class="brush:php;toolbar:false">基本上,只需使用EventSource設(shè)置客戶端,將服務(wù)器配置為正確格式的事件,然后在到達(dá)時處理消息。它很簡單,建在HTTP上,并得到廣泛支持。 <code>res.write(`id: ${eventId}\ndata: Hello\n\n`);</code><p></p>

以上是如何在HTML5中使用服務(wù)器量事件(SSE)?的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Stock Market GPT

Stock Market GPT

人工智能驅(qū)動投資研究,做出更明智的決策

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

熱門話題

如何在HTML5中使用服務(wù)器量事件(SSE)? 如何在HTML5中使用服務(wù)器量事件(SSE)? Sep 21, 2025 am 06:11 AM

SSEenablesreal-time,unidirectionalserver-to-clientupdatesviaHTTP;useEventSourceinJavaScripttoconnect,handlemessageswithonmessage,setserverresponsetypetotext/event-stream,formatdatawith"data:"and"\n\n",andoptionallyincludeeventIDsf

如何使用ARIA角色在HTML5中可訪問? 如何使用ARIA角色在HTML5中可訪問? Sep 21, 2025 am 04:41 AM

ARIAenhanceswebaccessibilitybyaddingsemanticmeaningtoelementswhennativeHTMLisinsufficient.UseARIAroleslikerole="button",aria-expanded,andaria-labelforcustomcomponentsordynamiccontent,butalwaysprefernativeHTMLelementssuchasbuttonornav.Update

如何管理HTML5中可訪問性的焦點(diǎn)? 如何管理HTML5中可訪問性的焦點(diǎn)? Sep 21, 2025 am 05:27 AM

UsesemanticHTMLelementslikeandfornativefocusabilityandkeyboardsupport.EnsurelogicaltaborderandvisiblefocusindicatorsviaCSS.Programmaticallymanagefocusindynamiccontentlikemodalsusingelement.focus(),trappingfocusinsideandreturningitafterclosure.ApplyAR

如何根據(jù)HTML5中的正則表達(dá)式驗證形式場? 如何根據(jù)HTML5中的正則表達(dá)式驗證形式場? Sep 22, 2025 am 05:11 AM

UsEthepatternattributeInhtml5InputElementStavalIdateAgainStareGex,SustAsForpassWordsRequiringNumbers,大寫,小寫,小寫和最小值; pairwithTitleForuserGuuserGuiDanceNanceNanceAgeAgeAgeAncuiredeNandAnceAndEnceAneandRequiredFornonOn-enon-emptement-emptentement-emptentement。

如何在HTML5文檔中對SVG路徑進(jìn)行動畫動畫? 如何在HTML5文檔中對SVG路徑進(jìn)行動畫動畫? Sep 21, 2025 am 01:58 AM

USECSSSTROKE-DASHARRAYAND和Strows-DashoffSetForsimpledrawingAnimations; 2.ApplyJavascriptForderynamicTriggerSlikeloadorsCroll; 3. 3. EmploylibrariesLibrariesLiblarieLikeGsapForPathMorphring; 4.4.ptimizeptimizeperanceBylimizeperanceBylimityBylimityConconcurrentanimations。

如何在HTML5表單中使用占位符屬性? 如何在HTML5表單中使用占位符屬性? Sep 23, 2025 am 05:17 AM

placeholderaterattributrovidesashorthintininputfields.itappearsfaintlyanddisappearspearspearspearspearpebebebebebebebebegins,supportEdIntext,電子郵件,tel,tel,search,andtextareAlements.useittoshowexamplease.useittoshowexampleslike example@email@email@email.com,butnotasareplacementforlacementforlabels.labelsensurebelsen.labelsensureb.labelserureb

如何構(gòu)建HTML5頁面? 如何構(gòu)建HTML5頁面? Sep 20, 2025 am 04:03 AM

AWELL結(jié)構(gòu)的HTML5PAGESTARTSWITHAND,隨后的byAsectionContaining,fiewportSettings,title和andcsslinks,thenawithsemanticelementslike,,,,,,, and forclearlayout,可訪問性和訪問性。

如何將所需屬性用于HTML5中的表單字段? 如何將所需屬性用于HTML5中的表單字段? Sep 24, 2025 am 02:56 AM

thequiredattributeinhtml5ensuresformfordsarefillebeforeSubmission,supportedbyInputTypyTypeslikeText,電子郵件,密碼,復(fù)選框,無線電,select,select和file;

See all articles