今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

Setting up socket.io

Chinwuba 2026年06月22日 02:23 3 次阅读 来源:Dev.to

This article covers what I learned or maybe didn't really learn. The Problem With Traditional HTTP Most web applications use HTTP. The flow looks like this: Client → Request → Server Client ← Response ← Server Once the server sends the response, the connection is closed. This works perfectly for: Authentication CRUD operations Fetching data Form submissions But what happens when the server needs to send information without being asked? For example: A new task is assigned Someone comments on a task A project status changes A teammate updates a board With traditional HTTP, the browser would need to keep asking: "Anything new?" "Anything new?" "Anything new?" This technique is called polling, and it's inefficient. That's where Socket.io comes in. What Socket.io Actually Does Socket.io creates a persistent connection between the client and server. Instead of repeatedly opening and closing connections, the connection stays alive. Now communication becomes two-way: Client ↔ Server The client can send data whenever it wants. The server can also send data whenever it wants. This is what makes real-time applications possible. Why Express Alone Isn't Enough One thing that confused me initially was why Socket.io couldn't simply be attached directly to my Express app. The answer lies in how Express works. When you write: app . listen ( 5000 ); Express creates the HTTP server internally. You don't have direct access to it. Socket.io, however, needs access to the raw HTTP server. So instead of: app . listen ( PORT ); The flow becomes: const httpServer = createServer ( app ); Then Socket.io attaches to that server: const io = new Server ( httpServer ); Finally: httpServer . listen ( PORT ); This architecture allows Socket.io and Express to share the same server. Understanding Events Socket.io is event-driven. Everything revolves around two methods: socket . emit () and socket . on () Think of them as: emit = send on = listen For example: Client: socket . emit ( " join-project " ,

本文内容来源于互联网,版权归原作者所有
查看原文