0Pricing
Real-Time Streaming Systems (WebRTC + Live Data) · 강의

양방향 흐름을 위한 WebSockets

클라이언트와 서버 간 실시간 양방향 데이터 교환에 적합한 전이중 통신 프로토콜인 WebSockets를 구현하고 이해합니다.

양방향 흐름을 위한 WebSockets은(는) CoddyKit의 무료 Real-Time Streaming Systems (WebRTC + Live Data) 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Real-Time Streaming Systems (WebRTC + Live Data) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Real-Time Streaming Systems (WebRTC + Live Data) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What are WebSockets?

Imagine a phone call where both people can talk and listen at the same time, without hanging up and redialing for each sentence. That's similar to a WebSocket connection!

WebSockets provide a full-duplex communication channel over a single, long-lived connection. This means data can flow in both directions simultaneously, making real-time interactions smooth and efficient.

Beyond HTTP: Bidirectional Flow

Traditional HTTP communication works like sending a letter and waiting for a reply. Each request is separate.

  • HTTP: Client sends a request, server sends a response. Connection usually closes.
  • WebSockets: Once connected, client and server can send messages to each other at any time, without needing a new request/response cycle. The connection stays open.

This persistent, bidirectional nature is crucial for live updates.

Establishing a WebSocket

A WebSocket connection starts with a standard HTTP request, but it includes a special header to 'upgrade' the connection.

This process is called the WebSocket Handshake:

  1. Client sends an HTTP request with an 'Upgrade' header.
  2. Server responds with a '101 Switching Protocols' status.
  3. The connection then becomes a persistent WebSocket connection.

After the handshake, the underlying TCP connection is used for direct WebSocket message exchange.

Your Browser's WebSocket API

In web browsers, you interact with WebSockets using the built-in WebSocket API. It's a JavaScript object that handles the connection details for you.

You create a new WebSocket instance by providing the URL of your WebSocket server. This URL typically starts with ws:// for unencrypted or wss:// for encrypted connections (secure WebSockets).

Connecting to a Server

Let's see how to establish a basic WebSocket connection from your browser. We'll connect to a public echo server that simply sends back whatever it receives.

Try running this example. You should see 'Connected!' when the connection is established.

<!DOCTYPE html>
<html>
<head>
  <title>WebSocket Connect</title>
</head>
<body>
  <h1>Connecting...</h1>
  <script>
    // Use wss:// for secure connections
    const socket = new WebSocket('wss://echo.websocket.events');

    socket.onopen = () => {
      document.querySelector('h1').innerText = 'Connected!';
      console.log('WebSocket connection opened');
    };

    socket.onerror = (error) => {
      document.querySelector('h1').innerText = 'Error!';
      console.error('WebSocket Error:', error);
    };
  </script>
</body>
</html>

Sending Data to the Server

Once connected, you can send data to the WebSocket server using the send() method of your WebSocket object. You can send text, binary data, or even JSON strings.

In this example, type a message and click 'Send'. The echo server will receive it.

<!DOCTYPE html>
<html>
<head>
  <title>Send WebSocket</title>
</head>
<body>
  <input type="text" id="messageInput" placeholder="Type a message">
  <button onclick="sendMessage()">Send</button>
  <p id="status"></p>
  <script>
    const socket = new WebSocket('wss://echo.websocket.events');

    socket.onopen = () => {
      document.getElementById('status').innerText = 'Connected. Send a message!';
    };

    function sendMessage() {
      const input = document.getElementById('messageInput');
      const message = input.value;
      if (socket.readyState === WebSocket.OPEN) {
        socket.send(message);
        document.getElementById('status').innerText = 'Sent: ' + message;
        input.value = ''; // Clear input after sending
      } else {
        document.getElementById('status').innerText = 'Not connected yet!';
      }
    }
  </script>
</body>
</html>

Receiving Server Updates

To receive messages from the server, you listen for the message event using socket.onmessage. The event object contains the received data.

Run this code. It sends a message on open, and then displays the echo server's response.

<!DOCTYPE html>
<html>
<head>
  <title>Receive WebSocket</title>
</head>
<body>
  <h1>Echo Messages</h1>
  <ul id="messages"></ul>
  <script>
    const socket = new WebSocket('wss://echo.websocket.events');

    socket.onopen = () => {
      console.log('WebSocket connection opened.');
      // Send a message to get a response from the echo server
      socket.send('Hello Echo Server!'); 
    };

    socket.onmessage = (event) => {
      const messageList = document.getElementById('messages');
      const newItem = document.createElement('li');
      newItem.textContent = 'Received: ' + event.data;
      messageList.appendChild(newItem);
    };

    socket.onerror = (error) => {
      console.error('WebSocket Error:', error);
    };
  </script>
</body>
</html>

Closing WebSockets Gracefully

It's good practice to manage your WebSocket connections. You can close a connection using the socket.close() method.

Additionally, you can listen for other events:

  • socket.onclose: Fired when the connection is closed.
  • socket.onerror: Fired if an error occurs during connection.

Properly handling these events helps build robust real-time applications.

Where WebSockets Shine

WebSockets are perfect for applications that need instant, continuous updates between clients and servers. Common use cases include:

  • Real-time chat applications: Messages appear instantly for all participants.
  • Live sports scores/stock tickers: Data updates without page refreshes.
  • Multiplayer online games: Synchronizing game state and player actions.
  • Collaborative editing: Seeing changes from others in real-time.

They provide a more efficient alternative to repeatedly polling a server.

WebSocket Knowledge Check

You've learned about WebSockets. Let's test your understanding!

WebSockets Summary

Great job! In this lesson, you explored WebSockets, a powerful technology for real-time communication.

  • WebSockets provide full-duplex, bidirectional communication.
  • They establish a persistent connection after an HTTP handshake.
  • The browser's WebSocket API allows you to connect, send, and receive messages.
  • WebSockets are ideal for applications needing instant, continuous updates.

Next, you'll delve into practical applications of data channels in WebRTC!

자주 묻는 질문

“양방향 흐름을 위한 WebSockets” 강의는 무료인가요?

네 — “양방향 흐름을 위한 WebSockets” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Real-Time Streaming Systems (WebRTC + Live Data) 강의 전체를 잠금 해제할 수 있습니다. Real-Time Streaming Systems (WebRTC + Live Data) 강의에는 총 4개의 강의가 포함되어 있습니다.

“양방향 흐름을 위한 WebSockets”에서 뭘 배우나요?

클라이언트와 서버 간 실시간 양방향 데이터 교환에 적합한 전이중 통신 프로토콜인 WebSockets를 구현하고 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Real-Time Streaming Systems (WebRTC + Live Data)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Real-Time Streaming Systems (WebRTC + Live Data)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Real-Time Streaming Systems (WebRTC + Live Data)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“양방향 흐름을 위한 WebSockets” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Real-Time Streaming Systems (WebRTC + Live Data) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Real-Time Streaming Systems (WebRTC + Live Data) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 실시간 데이터와 기존 HTTP 비교
  2. 양방향 흐름을 위한 WebSockets
  3. 단방향 푸시를 위한 Server-Sent Events(SSE)
  4. 롱 폴링과 스트리밍으로의 발전
← Real-Time Streaming Systems (WebRTC + Live Data)(으)로 돌아가기