0Pricing
Real-Time Streaming Systems (WebRTC + Live Data) · 课时

用于双向数据流的 WebSockets

实现并理解 WebSockets。这是一种全双工通信协议,非常适合客户端与服务器之间实时交换双向数据。

用于双向数据流的 WebSockets 是 CoddyKit 上的免费 Real-Time Streaming Systems (WebRTC + Live Data) 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Real-Time Streaming Systems (WebRTC + Live Data) 课程的其余内容,请升级到 CoddyKit PRO。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。

「用于双向数据流的 WebSockets」这节课中我会学到什么?

实现并理解 WebSockets。这是一种全双工通信协议,非常适合客户端与服务器之间实时交换双向数据。 你通过在浏览器中直接运行的动手代码来练习 Real-Time Streaming Systems (WebRTC + Live Data),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Real-Time Streaming Systems (WebRTC + Live Data) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Real-Time Streaming Systems (WebRTC + Live Data) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「用于双向数据流的 WebSockets」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Real-Time Streaming Systems (WebRTC + Live Data) 课中编写并运行代码吗?

能。每节 Real-Time Streaming Systems (WebRTC + Live Data) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 实时数据与传统 HTTP
  2. 用于双向数据流的 WebSockets
  3. 用于单向推送的服务器发送事件(SSE)
  4. 长轮询及其向流式传输的发展
← 返回 Real-Time Streaming Systems (WebRTC + Live Data)