搜索
首页web前端js教程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

Backstory: The Unexpected Interview Question

A few months ago, I was in the middle of a technical interview for a mid-level front-end position. Things were going smoothly until I was hit with a question that caught me slightly off guard.

"Imagine you need a form of constant communication to check something every second until you retrieve something you need.

For example, you want to keep checking if a payment has been successful, like in an e-commerce setup. How would you approach this?"

I responded cautiously, “I think you could implement WebSockets to handle that.”

The interviewer smiled. "That’s a good solution, but there are other, arguably better, options depending on the situation."

And that’s when we dove into a conversation about various approaches to real-time communication, including Long Polling, Short Polling, WebSockets, and finally, Server-Sent Events (SSE), which is arguably the best choice for a unidirectional data stream, like in our payment example.

We also discussed choosing the right database for handling these constant, yet lightweight requests without draining server resources. In that context, Redis came up, known for its simplicity and efficiency in managing these types of requests.

This conversation stuck with me. I realized that while WebSockets get a lot of attention, there’s a wide array of techniques that, when understood, can optimize the way we manage real-time communication. Today, I want to break down these four approaches, when to use each, and their pros and cons in a clear, engaging way. By the end, you’ll have a solid understanding of why Server-Sent Events (SSE) often shine for one-way, real-time communication.

Before I begin, huge thanks to Marcos, the experienced Senior Software Engineer who conducted that chat and inspired me to write this article months later, which I much appreciated even though I didn't get the job! :)


The Four Methods of Real-Time Communication

Before jumping into the SSE example, let’s break down the four methods we discussed during that interview:

1. Short Polling

Short polling is probably the simplest method. It involves making a request to the server at regular intervals, asking, “Do you have new data?” The server responds with the current state—whether or not there’s anything new.

Upside:

  • Easy to implement
  • Works with traditional HTTP requests

Downside:

  • It’s resource-heavy. You’re making frequent requests, even when no new data is available.
  • Can increase server load and network traffic, which becomes inefficient for frequent checks like payment status updates.

Best for: Small, low-frequency data updates, such as a stock market price to update every minute or so.

2. Long Polling

Long polling takes short polling a step further. The client repeatedly requests information from the server, but instead of the server responding right away, it holds onto the connection until new data is available. Once data is sent back, the client immediately opens a new connection and repeats the process.

Upside:

  • More efficient than short polling because the server only responds when necessary - it's really fast.
  • Compatible with browsers and HTTP/HTTPS protocols.

Downside:

  • Still requires reopening connections repeatedly, leading to inefficiency over time - expensive resources.
  • Slightly more complex than short polling.

Best for: Situations where real-time communication is needed but WebSockets/SSE might be overkill (e.g., chat applications).

3. WebSockets

WebSockets are a more modern solution that provides full-duplex communication between client and server. Once a connection is opened, both sides can send data freely without re-establishing connections - which defines a bidirectional communication.

Upside:

  • True real-time communication with minimal latency.
  • Great for bi-directional communication (e.g., real-time games, chat apps).

Downside:

  • 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>
  );
}

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",
    },
  });
}

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

NEXT_PUBLIC_DOMAIN_URL='http://localhost:3000'

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!


Let's get our hands dirty

Next.js + TypeScript example repository: https://github.com/brinobruno/sse-next
Next.js + TypeScript example deployment: https://sse-next-one.vercel.app/

References

here are some authoritative sources and references you could explore for deeper insights:

WebSockets And SSE Documentation:

MDN Web Docs: The WebSockets API
MDN Web Docs: Using Server Sent Events

Next API Routes

Next.js: API Routes


Let's connect

I'll share my relevant socials in case you want to connect:
Github
LinkedIn
Portfolio

以上是Real-Time Web Communication: Long/Short Polling, WebSockets, and SSE Explained + Next.js code的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
C和JavaScript:连接解释C和JavaScript:连接解释Apr 23, 2025 am 12:07 AM

C 和JavaScript通过WebAssembly实现互操作性。1)C 代码编译成WebAssembly模块,引入到JavaScript环境中,增强计算能力。2)在游戏开发中,C 处理物理引擎和图形渲染,JavaScript负责游戏逻辑和用户界面。

从网站到应用程序:JavaScript的不同应用从网站到应用程序:JavaScript的不同应用Apr 22, 2025 am 12:02 AM

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

Python vs. JavaScript:比较用例和应用程序Python vs. JavaScript:比较用例和应用程序Apr 21, 2025 am 12:01 AM

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。

C/C在JavaScript口译员和编译器中的作用C/C在JavaScript口译员和编译器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

JavaScript在行动中:现实世界中的示例和项目JavaScript在行动中:现实世界中的示例和项目Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

了解JavaScript引擎:实施详细信息了解JavaScript引擎:实施详细信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python vs. JavaScript:学习曲线和易用性Python vs. JavaScript:学习曲线和易用性Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中