導入
Server-Sent Events (SSE) は、サーバーが HTTP 経由でクライアントにリアルタイムの更新をプッシュできるようにする Web テクノロジーです。 WebSocket とは異なり、SSE はサーバーからブラウザへの一方向通信チャネルを使用し、通常の HTTP 接続で動作するため、実装が簡単です。これは、ライブ スコア、通知、リアルタイム モニタリング ダッシュボードなど、定期的な更新が必要なアプリケーションに特に役立ちます。
このデモを作成したのは、現在 AI がさまざまなトピックについて話し合うアプリケーションを開発しているためです。ストリームのような機能を実装したいと考えていたところ、「SSE」というテクノロジーを発見しました。
デモの概要
このデモでは、サーバー送信イベント (SSE) を使用して API からブラウザーにリアルタイムの更新を送信する方法を紹介します。この例では、サーバーから送信された一連のサンプル メッセージがブラウザーに表示されます。このデモはシンプルなので、SSE の仕組みを理解し、プロジェクトに統合するための優れた出発点となります。
デモビデオ
以下は、Server-Sent Events (SSE) デモがリアルタイムでどのように動作するかを示すビデオです。このビデオを見ると、クライアントとサーバーがどのように対話してリアルタイムの更新を提供するかについてよりよく理解できます。
実装
Server-Sent Events (SSE) デモのコア実装は、フロントエンドとバックエンドの 2 つの部分に分かれています。完全なソース コードは、GitHub: sse-demo リポジトリで入手できます。
フロントエンド (ui/src/app/page.tsx)
フロントエンドは React で構築されており、SSE 接続を開始および停止するボタンを提供し、サーバーからのリアルタイム メッセージを表示します。主なハイライトは次のとおりです:
-
SSE への接続: handleStartConnection 関数は、/events エンドポイントに接続された EventSource オブジェクトを作成します。メッセージ、オープン イベント、エラー イベントをリッスンします:
- onmessage: 受信メッセージを処理し、メッセージの状態を更新します。
- onopen: 接続が確立されたときのログを記録します。
- onerror: エラーを処理し、詳細をログに記録し、必要に応じて接続を閉じます。
接続の停止: handleStopConnection 関数は SSE 接続を閉じてクリーンアップします。
UI: このページには、開始/停止ボタンとメッセージを表示するリストを備えたシンプルなインターフェイスが含まれています。
"use client"; import type React from "react"; import { useState } from "react"; const App: React.FC = () => { const [messages, setMessages] = useState<string>([]); const [eventSource, setEventSource] = useState<eventsource null>(null); const handleStartConnection = () => { const newEventSource = new EventSource("http://localhost:8080/events"); const handleOnMessage = (event: MessageEvent) => { console.log("onmessage", event.data); setMessages((prev) => [...prev, event.data]); }; const handleOnOpen = () => { console.log("Connection established"); }; const handleOnError = (error: Event) => { console.error("onerror", error); console.log("readyState:", newEventSource.readyState); console.log("Connection error occurred."); newEventSource.close(); setEventSource(null); }; const handleOnClose = () => { console.log("Connection is being closed by the server."); newEventSource.close(); setEventSource(null); }; newEventSource.onmessage = handleOnMessage; newEventSource.onopen = handleOnOpen; newEventSource.onerror = handleOnError; newEventSource.addEventListener("close", handleOnClose); setEventSource(newEventSource); }; const handleStopConnection = () => { if (eventSource) { eventSource.close(); setEventSource(null); console.log("Connection closed"); } }; return ( <div> <h1 id="Server-Sent-Events-Demo">Server-Sent Events Demo</h1> <button type="button" onclick="{handleStartConnection}" disabled classname="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50"> Start Connection </button> <button type="button" onclick="{handleStopConnection}" disabled classname="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50 ml-2"> Stop Connection </button> <ul> {messages.map((message, index) => ( <li key="{`${index}-${message}`}">{message}</li> ))} </ul> </div> ); }; export default App; </eventsource></string>
バックエンド (api/main.go)
バックエンドは Go 用の Jin フレームワークを使用して構築されており、次の主要な機能が含まれています。
CORS 構成: バックエンドは、Gin CORS ミドルウェアを使用して、デバッグ中の接続を許可します。
-
SSE エンドポイント: /events エンドポイントは、各メッセージの間に遅延を設けて、一連の事前定義されたメッセージをクライアントにストリーミングします。主要コンポーネント:
- ヘッダーは、テキスト/イベント ストリームのコンテンツ タイプを指定するように設定されます。
- メッセージはループで送信され、各メッセージ間に 2 秒の遅延が生じます。
- 最後の close イベントは、接続の終了を示します。
"use client"; import type React from "react"; import { useState } from "react"; const App: React.FC = () => { const [messages, setMessages] = useState<string>([]); const [eventSource, setEventSource] = useState<eventsource null>(null); const handleStartConnection = () => { const newEventSource = new EventSource("http://localhost:8080/events"); const handleOnMessage = (event: MessageEvent) => { console.log("onmessage", event.data); setMessages((prev) => [...prev, event.data]); }; const handleOnOpen = () => { console.log("Connection established"); }; const handleOnError = (error: Event) => { console.error("onerror", error); console.log("readyState:", newEventSource.readyState); console.log("Connection error occurred."); newEventSource.close(); setEventSource(null); }; const handleOnClose = () => { console.log("Connection is being closed by the server."); newEventSource.close(); setEventSource(null); }; newEventSource.onmessage = handleOnMessage; newEventSource.onopen = handleOnOpen; newEventSource.onerror = handleOnError; newEventSource.addEventListener("close", handleOnClose); setEventSource(newEventSource); }; const handleStopConnection = () => { if (eventSource) { eventSource.close(); setEventSource(null); console.log("Connection closed"); } }; return ( <div> <h1 id="Server-Sent-Events-Demo">Server-Sent Events Demo</h1> <button type="button" onclick="{handleStartConnection}" disabled classname="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50"> Start Connection </button> <button type="button" onclick="{handleStopConnection}" disabled classname="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded disabled:opacity-50 ml-2"> Stop Connection </button> <ul> {messages.map((message, index) => ( <li key="{`${index}-${message}`}">{message}</li> ))} </ul> </div> ); }; export default App; </eventsource></string>
実行方法
このデモを実行するには、GitHub リポジトリの README.md ファイルを参照してください。これには、プロジェクトのフロントエンドとバックエンドの両方を設定して実行するための段階的な手順が含まれています。
結論
このデモは、Server-Sent Events (SSE) のシンプルかつ効果的な紹介を提供し、サーバーからブラウザーにリアルタイム メッセージをストリーミングする方法を示します。基本に焦点を当てることで、核となる概念をすぐに理解し、独自のプロジェクトで SSE の実験を開始できるように設計されています。
この例を試してみたり、この例に基づいて構築したりすることに興味がある場合は、GitHub の完全なソース コード (sse-demo リポジトリ) をチェックしてください。
以上がSSE(Server-Send Events)の最も簡単なデモの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

fatestinggocodewithinit functions、useexplicitsetupfunctionsurseSorseparatet fileStoavoidepencyonInitonitisideEffects.1)useexplicitsetupfuncontrollglobalbariaveInitialization.2)createSeparateSteSteSteStobypassInit funtedtententen

Go'serrorhandlingReturnserrorsasasvalues、javaandpython whichuseexceptions.1)go'smethodensuresexpliciterror handling

効果的なインターフェイスリングミニマル、クリア、およびプロモテスルーシューリング。1)インターフェイスForfforfibilityOfimplementation.2)interfacesforact forabstractiontoswapimplementations withingingcallingcode.3)設計の快適性を発信すること

集中型エラー処理は、GO言語でのコードの読みやすさと保守性を向上させることができます。その実装方法と利点には、次のものが含まれます。1。ビジネスロジックからロジックを個別に処理し、コードを簡素化します。 2。中央の取り扱いによるエラー処理の一貫性を確保します。 3. DeferとRecoverを使用してパニックをキャプチャおよび処理して、プログラムの堅牢性を高めます。

Ingo、AlternativestoinititionCustomInitializationAndSingletons.1)CustomInitializationAltionsionAlowoveroveroveroveroveroveroveroveroveroveroveroveroveroveroveroverover curs、beantefordedorcontionalsetups.2)singletonsensureone-initializatializatializatialent

gohandlesinterfacesandtypeassertionseffectivivivivivity、強化された柔軟性と耐毒性を強化します

言語エラー処理は、エラーとエラーを介してより柔軟になり、読みやすくなります。 1.エラーは、エラーが指定されたエラーと同じであり、エラーチェーンの処理に適しているかどうかを確認するために使用されます。 2.エラー。エラータイプを確認するだけでなく、エラーを特定のタイプに変換することもできます。これは、エラー情報を抽出するのに便利です。これらの関数を使用すると、エラー処理ロジックを簡素化できますが、エラーチェーンの正しい配信に注意を払い、コードの複雑さを防ぐために過度の依存性を回避できます。

tomakegogoapplicationsRunfasterAndMore -efficient、useprofilingtools、leverageconconcurrency、andmanagememoryefcectively.1)useprofforcpuandmemoryprofilingtoidentififybottlenecks.2)


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

SublimeText3 中国語版
中国語版、とても使いやすい

MantisBT
Mantis は、製品の欠陥追跡を支援するために設計された、導入が簡単な Web ベースの欠陥追跡ツールです。 PHP、MySQL、Web サーバーが必要です。デモおよびホスティング サービスをチェックしてください。

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

mPDF
mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

ホットトピック









