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

Çift Yönlü Akış için WebSockets

İstemci ile sunucu arasında gerçek zamanlı çift yönlü veri alışverişi için ideal, tam çift yönlü bir iletişim protokolü olan WebSockets'i uygulayın ve anlayın.

Çift Yönlü Akış için WebSockets, CoddyKit'te ücretsiz bir Real-Time Streaming Systems (WebRTC + Live Data) dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Real-Time Streaming Systems (WebRTC + Live Data) öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Real-Time Streaming Systems (WebRTC + Live Data) kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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!

Sıkça Sorulan Sorular

“Çift Yönlü Akış için WebSockets” dersi ücretsiz mi?

Evet — “Çift Yönlü Akış için WebSockets” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Real-Time Streaming Systems (WebRTC + Live Data) kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Real-Time Streaming Systems (WebRTC + Live Data) kursu toplamda 4 dersten oluşur.

“Çift Yönlü Akış için WebSockets” dersinde ne öğreneceğim?

İstemci ile sunucu arasında gerçek zamanlı çift yönlü veri alışverişi için ideal, tam çift yönlü bir iletişim protokolü olan WebSockets'i uygulayın ve anlayın. Real-Time Streaming Systems (WebRTC + Live Data) ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Real-Time Streaming Systems (WebRTC + Live Data) öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Real-Time Streaming Systems (WebRTC + Live Data), başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Çift Yönlü Akış için WebSockets” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Real-Time Streaming Systems (WebRTC + Live Data) dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Real-Time Streaming Systems (WebRTC + Live Data) dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Canlı Veri ve Geleneksel HTTP
  2. Çift Yönlü Akış için WebSockets
  3. Tek Yönlü İletim için Server-Sent Events (SSE)
  4. Uzun Yoklama ve Akışa Doğru Gelişim
← Real-Time Streaming Systems (WebRTC + Live Data) Sayfasına Dön