Home Web Front-end JS Tutorial Real-Time Web Communication: Long/Short Polling, WebSockets, and SSE Explained + Next.js code

Real-Time Web Communication: Long/Short Polling, WebSockets, and SSE Explained + Next.js code

Sep 23, 2024 pm 10:30 PM

Real-Time Web Communication: Long/Short Polling, WebSockets, and SSE Explained + Next.js code

Backstory: Soalan Temuduga Yang Tidak Dijangka

Beberapa bulan yang lalu, saya berada di tengah-tengah temuduga teknikal untuk kedudukan bahagian hadapan peringkat pertengahan. Semuanya berjalan lancar sehingga saya dipukul dengan soalan yang membuat saya sedikit terkejut.

"Bayangkan anda memerlukan satu bentuk komunikasi berterusan untuk memeriksa sesuatu setiap saat sehingga anda mendapatkan sesuatu yang anda perlukan.

Sebagai contoh, anda ingin terus menyemak sama ada pembayaran telah berjaya, seperti dalam persediaan e-dagang. Bagaimana anda akan mendekati ini?"

Saya menjawab dengan berhati-hati, "Saya rasa anda boleh melaksanakan WebSockets untuk mengendalikannya."

Pewawancara tersenyum. "Itu penyelesaian yang baik, tetapi ada pilihan lain, boleh dikatakan lebih baik, bergantung pada keadaan."

Dan ketika itulah kami menyelami perbualan tentang pelbagai pendekatan kepada komunikasi masa nyata, termasuk Tinjauan Panjang, Tinjauan Pendek, Soket Web, dan akhirnya, Acara Dihantar Pelayan (SSE), yang boleh dikatakan pilihan terbaik untuk aliran data satu arah, seperti dalam contoh pembayaran kami.

Kami juga membincangkan memilih pangkalan data yang betul untuk mengendalikan permintaan yang berterusan namun ringan ini tanpa menghabiskan sumber pelayan. Dalam konteks itu, Redis muncul, yang terkenal dengan kesederhanaan dan kecekapannya dalam mengurus jenis permintaan ini.

Perbualan ini melekat pada saya. Saya menyedari bahawa walaupun WebSockets mendapat banyak perhatian, terdapat pelbagai teknik yang, apabila difahami, boleh mengoptimumkan cara kami mengurus komunikasi masa nyata. Hari ini, saya ingin memecahkan empat pendekatan ini, bila hendak menggunakan setiap satu, dan kebaikan dan keburukannya dengan cara yang jelas dan menarik. Pada akhirnya, anda akan mempunyai pemahaman yang kukuh tentang sebab Acara Dihantar Pelayan (SSE) sering bersinar untuk komunikasi sehala, masa nyata.

Sebelum saya memulakan, terima kasih yang tidak terhingga kepada Marcos, Jurutera Perisian Kanan berpengalaman yang mengendalikan sembang itu dan memberi inspirasi kepada saya untuk menulis artikel ini beberapa bulan kemudian, yang saya amat hargai walaupun saya tidak mendapat pekerjaan itu! :)


Empat Kaedah Komunikasi Masa Nyata

Sebelum beralih ke contoh SSE, mari kita pecahkan empat kaedah yang kita bincangkan semasa temu bual itu:

1. Polling Ringkas

Tinjauan pendek mungkin kaedah yang paling mudah. Ia melibatkan membuat permintaan kepada pelayan secara berkala, bertanya, "Adakah anda mempunyai data baharu?" Pelayan bertindak balas dengan keadaan semasa—sama ada terdapat sesuatu yang baharu atau tidak.

Terbalik:

  • Mudah untuk dilaksanakan
  • Berfungsi dengan permintaan HTTP tradisional

Keburukan:

  • Memang berat sumber. Anda kerap membuat permintaan, walaupun tiada data baharu tersedia.
  • Boleh meningkatkan beban pelayan dan trafik rangkaian, yang menjadi tidak cekap untuk pemeriksaan kerap seperti kemas kini status pembayaran.

Terbaik untuk: Kemas kini data kecil dan frekuensi rendah, seperti harga pasaran saham untuk dikemas kini setiap minit atau lebih.

2. Pengundian Lama

Tinjauan panjang memerlukan pengundian pendek selangkah lagi. Pelanggan berulang kali meminta maklumat daripada pelayan, tetapi bukannya pelayan bertindak balas serta-merta, ia memegang sambungan sehingga data baharu tersedia. Sebaik sahaja data dihantar semula, pelanggan segera membuka sambungan baharu dan mengulangi proses tersebut.

Terbalik:

  • Lebih cekap daripada tinjauan singkat kerana pelayan hanya bertindak balas apabila perlu - ia sangat pantas.
  • Serasi dengan penyemak imbas dan protokol HTTP/HTTPS.

Keburukan:

  • Masih memerlukan pembukaan semula sambungan berulang kali, yang membawa kepada ketidakcekapan dari semasa ke semasa - sumber yang mahal.
  • Sedikit lebih kompleks daripada tinjauan singkat.

Terbaik untuk: Situasi di mana komunikasi masa nyata diperlukan tetapi WebSockets/SSE mungkin berlebihan (cth., aplikasi sembang).

3. Soket Web

WebSockets ialah penyelesaian yang lebih moden yang menyediakan komunikasi dupleks penuh antara pelanggan dan pelayan. Setelah sambungan dibuka, kedua-dua pihak boleh menghantar data secara bebas tanpa mewujudkan semula sambungan - yang mentakrifkan komunikasi dua hala.

Terbalik:

  • Komunikasi masa nyata sebenar dengan kependaman minimum.
  • Sesuai untuk komunikasi dua arah (cth., permainan masa nyata, apl sembang).

Keburukan:

  • More complex to implement than polling or SSE.
  • WebSockets aren’t always ideal for one-way communication or less frequent updates, as they can consume resources by maintaining open connections.
  • May need firewall configuration.

Best for: Applications requiring constant two-way communication, like multiplayer games, collaborative tools, chat applications, or real-time notifications.

4. Server-Sent Events (SSE)

Finally, we come to Server-Sent Events (SSE), the hero of our payment example. SSE creates a one-way connection where the server sends updates to the client. Unlike WebSockets, this is unidirectional—the client doesn’t send data back.

Upside:

  • Ideal for one-way data streams like news feeds, stock tickers, or payment status updates.
  • Lightweight and simpler to implement than WebSockets.
  • Uses the existing HTTP connection, so it’s well-supported and firewall-friendly.

Downside:

  • Not suitable for bi-directional communication.
  • Some browsers (particularly older versions of IE) don’t fully support SSE.

Best for: Real-time updates where the client only needs to receive data, such as live scores, notifications, and our payment status example.


SSE in Action: Real-Time Payment Status with Next.js

Let’s get to the heart of the matter. I built a simple Next.js app to simulate a real-time payment process using Server-Sent Events (SSE). It demonstrates exactly how you can set up one-way communication to check the status of a payment and notify the user when the payment succeeds or fails.

It's a bit of a headache to set it up for Next since it works a bit differently than plain js so you can thank me later!

Here’s the setup:

Frontend: Transaction Control Component

In the following component, we have a simple UI displaying buttons to simulate different types of transactions that would come from an actual gateway API (Pix, Stripe, and a failing credit card payment). These buttons trigger real-time payment status updates through SSE.

Here’s where the SSE magic happens. When a payment is simulated, the client opens an SSE connection to listen for updates from the server. It handles different statuses like pending, in transit, paid, and failed.

"use client";

import { useState } from "react";
import { PAYMENT_STATUSES } from "../utils/payment-statuses";

const paymentButtons = [
  {
    id: "pix",
    label: "Simulate payment with Pix",
    bg: "bg-green-200",
    success: true,
  },
  {
    id: "stripe",
    label: "Simulate payment with Stripe",
    bg: "bg-blue-200",
    success: true,
  },
  {
    id: "credit",
    label: "Simulate failing payment",
    bg: "bg-red-200",
    success: false,
  },
];

type transaction = {
  type: string;
  amount: number;
  success: boolean;
};

const DOMAIN_URL = process.env.NEXT_PUBLIC_DOMAIN_URL;

export function TransactionControl() {
  const [status, setStatus] = useState<string>("");
  const [isProcessing, setIsProcessing] = useState<boolean>(false);

  async function handleTransaction({ type, amount, success }: transaction) {
    setIsProcessing(true);
    setStatus("Payment is in progress...");

    const eventSource = new EventSource(
      `${DOMAIN_URL}/payment?type=${type}&amount=${amount}&success=${success}`
    );

    eventSource.onmessage = (e) => {
      const data = JSON.parse(e.data);
      const { status } = data;

      console.log(data);

      switch (status) {
        case PAYMENT_STATUSES.PENDING:
          setStatus("Payment is in progress...");
          break;
        case PAYMENT_STATUSES.IN_TRANSIT:
          setStatus("Payment is in transit...");
          break;
        case PAYMENT_STATUSES.PAID:
          setIsProcessing(false);
          setStatus("Payment completed!");
          eventSource.close();
          break;
        case PAYMENT_STATUSES.CANCELED:
          setIsProcessing(false);
          setStatus("Payment failed!");
          eventSource.close();
          break;
        default:
          setStatus("");
          setIsProcessing(false);
          eventSource.close();
          break;
      }
    };
  }

  return (
    <div>
      <div className="flex flex-col gap-3">
        {paymentButtons.map(({ id, label, bg, success }) => (
          <button
            key={id}
            className={`${bg} text-background rounded-full font-medium py-2 px-4
            disabled:brightness-50 disabled:opacity-50`}
            onClick={() =>
              handleTransaction({ type: id, amount: 101, success })
            }
            disabled={isProcessing}
          >
            {label}
          </button>
        ))}
      </div>

      {status && <div className="mt-4 text-lg font-medium">{status}</div>}
    </div>
  );
}

Copy after login

Backend: SSE Implementation in Next.js

On the server side, we simulate a payment process by sending periodic status updates through SSE. As the transaction progresses, the client will receive updates on whether the payment is still pending, has been completed, or has failed.

import { NextRequest, NextResponse } from "next/server";

import { PAYMENT_STATUSES } from "../utils/payment-statuses";

export const runtime = "edge";
export const dynamic = "force-dynamic";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function GET(req: NextRequest, res: NextResponse) {
  const { searchParams } = new URL(req.url as string);
  const type = searchParams.get("type") || null;
  const amount = parseFloat(searchParams.get("amount") || "0");
  const success = searchParams.get("success") === "true";

  if (!type || amount < 0) {
    return new Response(JSON.stringify({ error: "invalid transaction" }), {
      status: 400,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }
  const responseStream = new TransformStream();
  const writer = responseStream.writable.getWriter();
  const encoder = new TextEncoder();
  let closed = false;

  function sendStatus(status: string) {
    writer.write(
      encoder.encode(`data: ${JSON.stringify({ status, type, amount })}\n\n`)
    );
  }

  // Payment gateway simulation
  async function processTransaction() {
    sendStatus(PAYMENT_STATUSES.PENDING);

    function simulateSuccess() {
      setTimeout(() => {
        if (!closed) {
          sendStatus(PAYMENT_STATUSES.IN_TRANSIT);
        }
      }, 3000);

      setTimeout(() => {
        if (!closed) {
          sendStatus(PAYMENT_STATUSES.PAID);

          // Close the stream and mark closed to prevent further writes
          writer.close();
          closed = true;
        }
      }, 6000);
    }

    function simulateFailure() {
      setTimeout(() => {
        if (!closed) {
          sendStatus(PAYMENT_STATUSES.CANCELED);

          // Close the stream and mark closed to prevent further writes
          writer.close();
          closed = true;
        }
      }, 3000);
    }

    if (success === false) {
      simulateFailure();
      return;
    }

    simulateSuccess();
  }

  await processTransaction();

  // Return the SSE response
  return new Response(responseStream.readable, {
    headers: {
      "Access-Control-Allow-Origin": "*",
      Connection: "keep-alive",
      "X-Accel-Buffering": "no",
      "Content-Type": "text/event-stream; charset=utf-8",
      "Cache-Control": "no-cache, no-transform",
      "Content-Encoding": "none",
    },
  });
}
Copy after login

Also, make sure you add .env.local file with this content:

NEXT_PUBLIC_DOMAIN_URL='http://localhost:3000'
Copy after login

Why SSE Over WebSockets in This Case?

Now that we’ve seen how to implement it, you might be wondering: why use SSE over WebSockets for this? Here’s why:

  • Unidirectional Communication: In our scenario, the client only needs to receive updates about the payment status. There’s no need for the client to send data back to the server constantly, so the simplicity of SSE fits perfectly.
  • Lightweight: Since SSE uses a single HTTP connection to stream updates, it’s more resource-efficient compared to WebSockets, which maintain full-duplex communication.
  • Firewall-Friendly: SSE is easier to work with across different network environments because it runs over HTTP, which is usually open in firewalls, whereas WebSocket connections can sometimes run into issues.
  • Browser Support: While not as widely supported as WebSockets, SSE is supported by modern browsers, making it reliable for most use cases where unidirectional data is needed.

Conclusion: Know Your Tools

That interview question turned into an incredible learning experience, opening my eyes to the subtle differences between long polling, short polling, WebSockets, and SSE. Each method has its time and place, and understanding when to use which one is crucial for optimizing real-time communication.

SSE might not be as glamorous as WebSockets, but when it comes to efficient, one-way communication, it's the perfect tool for the job—just like in our e-commerce payment example. Next time you're building something that requires real-time updates, don’t just reach for WebSockets by default—consider SSE for its simplicity and efficiency.

Hope this deep dive into real-time communication techniques keeps you sharp for your next project or that tricky interview question!


讓我們動手吧

Next.js + TypeScript 範例儲存庫:https://github.com/brinobruno/sse-next
Next.js + TypeScript 部署範例:https://sse-next-one.vercel.app/

參考

以下是一些權威來源和參考資料,您可以探索以獲得更深入的見解:

WebSockets 和 SSE 文件:

MDN Web 文件:WebSockets API
MDN Web 文件:使用伺服器傳送的事件

下一個 API 路由

Next.js:API 路由


讓我們聯絡吧

如果您想聯繫,我會分享我的相關社交活動:
GitHub
領英
投資組合

The above is the detailed content of Real-Time Web Communication: Long/Short Polling, WebSockets, and SSE Explained + Next.js code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles