웹 프론트엔드 JS 튜토리얼 WebSocket 및 Socket.IO: Node.js와의 실시간 통신

WebSocket 및 Socket.IO: Node.js와의 실시간 통신

Oct 09, 2024 pm 10:46 PM

WebSockets and Socket.IO: Real-Time Communication with Node.js

채팅 앱, 온라인 게임, 실시간 협업 도구와 같은 최신 애플리케이션에서는 실시간 커뮤니케이션이 필수적입니다. WebSocket은 단일 TCP 연결을 통해 전이중 통신 채널을 제공하므로 클라이언트와 서버 간에 실시간으로 데이터를 교환할 수 있습니다. 이 기사에서는 WebSocket과 그 사용 사례, Node.js에서 구현하는 방법을 설명합니다. 추가적으로, WebSocket 통신을 단순화하는 인기 라이브러리인 Socket.IO와 실제 예제를 함께 살펴보겠습니다.

이 기사에서 다룰 내용은 다음과 같습니다.

  1. 웹소켓이란 무엇인가요?
  2. WebSocket과 HTTP: 주요 차이점
  3. Node.js에서 WebSocket 서버 설정
  4. Socket.IO는 무엇이고 왜 사용해야 하나요?
  5. Socket.IO를 사용하여 실시간 채팅 애플리케이션을 설정합니다.
  6. WebSocket 및 Socket.IO 사용 사례.
  7. WebSocket 연결을 보호합니다.

WebSocket이란 무엇입니까?

WebSocket은 서버와 클라이언트가 언제든지 데이터를 보낼 수 있는 양방향 통신 프로토콜을 제공합니다. 클라이언트가 모든 통신을 시작하고 서버에서 데이터를 요청하는 HTTP와 달리 WebSocket은 지속적인 연결을 지원하므로 연결을 다시 설정하지 않고도 두 당사자가 지속적으로 데이터를 교환할 수 있습니다.

주요 특징:

  • 낮은 대기 시간: WebSocket은 연결이 열린 상태로 유지되어 대기 시간이 줄어들기 때문에 HTTP에 비해 오버헤드가 낮습니다.
  • 전이중: 서버와 클라이언트 모두 동시에 데이터를 보내고 받을 수 있습니다.
  • 지속적 연결: 각 요청이 새 연결을 여는 HTTP와 달리 WebSocket 연결은 일단 설정된 후에는 열린 상태로 유지됩니다.

WebSocket과 HTTP: 주요 차이점

두 프로토콜 모두 TCP를 통해 실행되지만 상당한 차이점이 있습니다.

Feature WebSockets HTTP
Connection Persistent, full-duplex Stateless, new connection for each request
Directionality Bi-directional (server and client communicate) Client to server only (server responds)
Overhead Low after connection establishment Higher due to headers with every request
Use Case Real-time applications (chats, games) Traditional websites, API requests
특징 웹소켓 HTTP 연결 지속적, 전이중 상태 비저장, 각 요청에 대한 새로운 연결 방향성 양방향(서버와 클라이언트 통신) 클라이언트에서 서버로만(서버가 응답) 오버헤드 연결 설정 후 낮음 모든 요청의 헤더로 인해 더 높아짐 사용 사례 실시간 애플리케이션(채팅, 게임) 기존 웹사이트, API 요청

Setting Up a WebSocket Server in Node.js

To create a WebSocket server, Node.js provides a built-in ws library that allows you to create a WebSocket server and establish communication with clients.

Installation:

npm install ws
로그인 후 복사

WebSocket Server Example:

const WebSocket = require('ws');

// Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });

// Listen for incoming connections
wss.on('connection', (ws) => {
    console.log('Client connected');

    // Send a message to the client
    ws.send('Welcome to the WebSocket server!');

    // Listen for messages from the client
    ws.on('message', (message) => {
        console.log(`Received: ${message}`);
        ws.send(`Echo: ${message}`);
    });

    // Handle connection closure
    ws.on('close', () => {
        console.log('Client disconnected');
    });
});

console.log('WebSocket server running on ws://localhost:8080');
로그인 후 복사

In this example:

  • A WebSocket server is created that listens on port 8080.
  • When a client connects, the server sends a welcome message and listens for messages from the client.
  • The server responds with an echo of the message received from the client.

Client-Side WebSocket:

On the client side, you can connect to the WebSocket server using JavaScript:

const socket = new WebSocket('ws://localhost:8080');

// Event listener for when the connection is established
socket.addEventListener('open', (event) => {
    socket.send('Hello Server!');
});

// Listen for messages from the server
socket.addEventListener('message', (event) => {
    console.log(`Message from server: ${event.data}`);
});
로그인 후 복사

What is Socket.IO, and Why Should You Use It?

Socket.IO is a library that makes WebSocket communication easier by providing:

  • Automatic fallback to long polling if WebSockets aren’t supported.
  • Built-in reconnection and error handling mechanisms.
  • Support for rooms and namespaces, which allow for segmented communication channels.

Installation:

npm install socket.io
로그인 후 복사

Setting Up a Socket.IO Server:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Listen for incoming connections
io.on('connection', (socket) => {
    console.log('New client connected');

    // Listen for messages from the client
    socket.on('message', (msg) => {
        console.log(`Message from client: ${msg}`);
        socket.emit('response', `Server received: ${msg}`);
    });

    // Handle disconnection
    socket.on('disconnect', () => {
        console.log('Client disconnected');
    });
});

// Start the server
server.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});
로그인 후 복사

In this code:

  • A basic Express server is created, and Socket.IO is integrated to handle real-time communication.
  • The server listens for client connections and responds to any messages sent.

Setting Up a Real-Time Chat Application Using Socket.IO

Let's build a simple real-time chat application using Socket.IO to demonstrate its power.

Server Code:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
    console.log('A user connected');

    // Broadcast when a user sends a message
    socket.on('chat message', (msg) => {
        io.emit('chat message', msg);
    });

    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

server.listen(3000, () => {
    console.log('Listening on *:3000');
});
로그인 후 복사

Client Code (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Socket.IO Chat</title>
    <script src="/socket.io/socket.io.js"></script>
</head>
<body>
    <h1>Real-time Chat</h1>
    <ul id="messages"></ul>
    <form id="chatForm">
        <input id="message" autocomplete="off" /><button>Send</button>
    </form>

    <script>
        const socket = io();

        // Listen for incoming chat messages
        socket.on('chat message', (msg) => {
            const li = document.createElement('li');
            li.textContent = msg;
            document.getElementById('messages').appendChild(li);
        });

        // Send chat message
        const form = document.getElementById('chatForm');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            const message = document.getElementById('message').value;
            socket.emit('chat message', message);
            document.getElementById('message').value = '';
        });
    </script>
</body>
</html>
로그인 후 복사

This simple chat application allows multiple users to connect and exchange messages in real-time. Messages sent by one user are broadcast to all other users connected to the server.

Use Cases for WebSockets and Socket.IO

WebSockets and Socket.IO are perfect for scenarios requiring real-time communication, including:

  • Chat Applications: Real-time messaging is made possible by WebSockets or Socket.IO.
  • Online Gaming: Multiplayer online games where players need to see updates in real-time.
  • Collaborative Editing: Applications like Google Docs use WebSockets to allow multiple users to edit documents simultaneously.
  • Live Dashboards: Real-time updates in dashboards for stock markets, sports scores, etc.

Securing WebSocket Connections

Like HTTP, WebSocket connections should be secured to protect sensitive data. This can be done by using wss:// (WebSocket Secure), which is essentially WebSockets over TLS (Transport Layer Security).

Steps to Secure WebSocket with TLS:

  1. Obtain an SSL Certificate from a Certificate Authority (CA).
  2. Update WebSocket Server to listen on wss:// instead of ws://.
  3. Configure NGINX or another reverse proxy to terminate the SSL and forward traffic to your WebSocket server.

Example NGINX configuration:

server {
    listen 443 ssl;
    server_name yourdomain.com;

    ssl_certificate /etc/ssl/certs/yourdomain.crt;
    ssl_certificate_key /etc/ssl/private/yourdomain.key;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
로그인 후 복사

This ensures that all WebSocket traffic is encrypted, protecting it from eavesdropping and tampering.

Conclusion

WebSockets and Socket.IO enable real-time communication between clients and servers, which is essential for modern applications requiring instant updates. By implementing WebSocket or Socket.IO-based solutions, you can build responsive and efficient applications such as chat systems, collaborative tools, and live dashboards.

In this article, we've covered the basics of WebSockets, the advantages of using Socket.IO, and how to create real-time applications in Node.js. Additionally, we've explored how to secure WebSocket connections to ensure data safety during transmission.

Mastering these technologies will open up numerous possibilities for building powerful, interactive, and scalable web applications.

위 내용은 WebSocket 및 Socket.IO: Node.js와의 실시간 통신의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

프론트 엔드 열 용지 영수증에 대한 차량 코드 인쇄를 만나면 어떻게해야합니까? 프론트 엔드 열 용지 영수증에 대한 차량 코드 인쇄를 만나면 어떻게해야합니까? Apr 04, 2025 pm 02:42 PM

프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

Demystifying JavaScript : 그것이하는 일과 중요한 이유 Demystifying JavaScript : 그것이하는 일과 중요한 이유 Apr 09, 2025 am 12:07 AM

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

누가 더 많은 파이썬이나 자바 스크립트를 지불합니까? 누가 더 많은 파이썬이나 자바 스크립트를 지불합니까? Apr 04, 2025 am 12:09 AM

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

Shiseido의 공식 웹 사이트와 같은 시차 스크롤 및 요소 애니메이션 효과를 달성하는 방법은 무엇입니까?
또는:
Shiseido의 공식 웹 사이트와 같은 페이지 스크롤과 함께 애니메이션 효과를 어떻게 달성 할 수 있습니까? Shiseido의 공식 웹 사이트와 같은 시차 스크롤 및 요소 애니메이션 효과를 달성하는 방법은 무엇입니까? 또는: Shiseido의 공식 웹 사이트와 같은 페이지 스크롤과 함께 애니메이션 효과를 어떻게 달성 할 수 있습니까? Apr 04, 2025 pm 05:36 PM

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

JavaScript의 진화 : 현재 동향과 미래 전망 JavaScript의 진화 : 현재 동향과 미래 전망 Apr 10, 2025 am 09:33 AM

JavaScript의 최신 트렌드에는 Typescript의 Rise, 현대 프레임 워크 및 라이브러리의 인기 및 WebAssembly의 적용이 포함됩니다. 향후 전망은보다 강력한 유형 시스템, 서버 측 JavaScript 개발, 인공 지능 및 기계 학습의 확장, IoT 및 Edge 컴퓨팅의 잠재력을 포함합니다.

JavaScript는 배우기가 어렵습니까? JavaScript는 배우기가 어렵습니까? Apr 03, 2025 am 12:20 AM

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

JavaScript를 사용하여 동일한 ID와 동일한 ID로 배열 요소를 하나의 객체로 병합하는 방법은 무엇입니까? JavaScript를 사용하여 동일한 ID와 동일한 ID로 배열 요소를 하나의 객체로 병합하는 방법은 무엇입니까? Apr 04, 2025 pm 05:09 PM

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

프론트 엔드 개발에서 VSCODE와 유사한 패널 드래그 앤 드롭 조정 기능을 구현하는 방법은 무엇입니까? 프론트 엔드 개발에서 VSCODE와 유사한 패널 드래그 앤 드롭 조정 기능을 구현하는 방법은 무엇입니까? Apr 04, 2025 pm 02:06 PM

프론트 엔드에서 VSCODE와 같은 패널 드래그 앤 드롭 조정 기능의 구현을 탐색하십시오. 프론트 엔드 개발에서 VSCODE와 같은 구현 방법 ...

See all articles