What is WebSocket? How is it used? What are its advantages? What are the differences between it and AJAX/Axios?

16 Aralık 2025 Salı - 09:00 (4 Saat önce)

WebSocket is a communication protocol supported by many modern web browsers and server platforms. This protocol enables bidirectional communication between a web browser and a server. While the traditional HTTP protocol uses a "request-response" model for client-to-server requests, with WebSocket, the server can also send data to the client. This is crucial for supporting real-time applications and interactive websites.

WebSocket provides bidirectional communication between a client and a server. Therefore, WebSocket technology operates between the client and the server. However, WebSocket support is required on the server side. Once a connection is established between the client and server, both parties can send and receive data. Consequently, to enable real-time communication using WebSocket, appropriate application code must exist on both the client and server sides. For example, a web browser can use WebSocket on the client side, while a web server can accept and handle WebSocket connections on the server side. In this way, it facilitates real-time communication using WebSocket.

The main features of WebSocket are:

Full Duplex Communication: Both the client and server can send data to each other after the connection is established.
Low Latency: WebSocket exchanges data directly without unnecessary extra header data like HTTP, thus resulting in lower latency.
Single Connection: A single connection can be used for multiple data exchanges, reducing the overhead of establishing unnecessary connections.
Protocol Extensibility: WebSocket can be customized and extended using protocol extensions.

WebSocket is used in a variety of scenarios that require real-time communication in web-based applications. It is ideal for applications such as live chat, online gaming, financial applications, and real-time analytics.

Some use cases for WebSocket:

  • Live Chat Applications: WebSocket is ideal for live chat applications where users can communicate in real-time. Fast sending and receiving of messages enhances the user experience.

  • Real-Time Games: Multiplayer online games require fast and continuous data exchange between players. WebSocket is ideal for processing user interactions in real-time in such games.

  • Financial Applications: Stock, cryptocurrency, and other financial asset prices change rapidly. Financial applications can use WebSocket to monitor market data in real-time and send instant notifications to users.

  • Real-Time Analytics: WebSocket can be used for big data processing and real-time analytics. For example, a streaming data analysis application can process incoming data instantly and display the results to users.

  • Remote Control and Monitoring: In applications like IoT devices and industrial control systems, WebSocket can be used for continuous communication with devices and status monitoring.

  • Drag-and-Drop File Upload: WebSocket can be used to monitor drag-and-drop file uploads in real-time and show progress to users.

These scenarios are just a few examples of WebSocket, and this technology is a suitable solution for many different applications requiring real-time communication in various fields.

WebSocket vs. AJAX and Axios
WebSocket is a different communication protocol compared to other HTTP-based communication methods like AJAX and Axios, and it has different use cases. Here is a comparison of WebSocket with AJAX and Axios:

Proximity and Real-Time Communication:

  • WebSocket: Ideal for real-time communication. It provides continuous, bidirectional communication between the server and client. This can be used in scenarios like live chat applications and real-time games.

  • AJAX and Axios: HTTP-based technologies like AJAX and Axios provide one-way communication with the server. The client sends a request to the server and receives a response. This is useful for exchanging data without refreshing a page but is not as suitable for real-time communication as WebSocket.

Data Traffic:

  • WebSocket: After establishing the connection, it sends and receives data without unnecessary header data. This results in lower data traffic and reduced latency.

  • AJAX and Axios: HTTP-based communication adds header data for each request. This can lead to increased data traffic and higher latency.

Connection Management:

  • WebSocket: Provides continuous communication over a single connection. Once the connection is established, there is no need to repeatedly reconnect for data exchange between client and server.

  • AJAX and Axios: Each request requires a separate HTTP request, making connection management more complex. This can lead to unnecessary connection overhead.

Supported Platforms:

  • WebSocket: Supported by modern web browsers and server platforms. However, some older browsers and server platforms do not support WebSocket.

  • AJAX and Axios: Supported by almost all web browsers and server platforms, providing broader compatibility.

In conclusion, WebSocket is ideal for applications requiring real-time communication but has a more specific use case compared to HTTP-based technologies. HTTP-based technologies like AJAX and Axios are more widely used for general-purpose data exchange.

Example Usage
This example demonstrates connecting from a JavaScript client to a WebSocket server and sending and receiving messages. In this example, we will create a simple WebSocket server using Node.js and then connect to this server using JavaScript in an HTML file.

WebSocket Server (Node.js):

const WebSocket = require('ws');

// WebSocket sunucusunu oluştur
const wss = new WebSocket.Server({ port: 8080 });

// Yeni bir bağlantı geldiğinde
wss.on('connection', function connection(ws) {
  console.log('Yeni bir bağlantı oluşturuldu.');

  // İstemciden gelen mesajları dinle
  ws.on('message', function incoming(message) {
    console.log('İstemciden mesaj alındı:', message);
    
    // Gelen mesajı geri gönder
    ws.send('Sunucudan alındı: ' + message);
  });
});

WebSocket Client (HTML and JavaScript):

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

    // Sunucudan gelen mesajları dinle
    socket.onmessage = function(event) {
      const outputDiv = document.getElementById('output');
      outputDiv.innerHTML += ' ' + event.data + ' ';

    };

 

    // Mesaj gönderme işlevi
    function sendMessage() {
      const inputField = document.getElementById('messageInput');
      const message = inputField.value;
      socket.send(message);
      inputField.value = ''; // input alanını temizle
    }

The above example creates a WebSocket server and connects to it using JavaScript within an HTML file on the client side. When the user enters their messages in a text input box and clicks the "Send Message" button, the client sends this message to the server and displays the response from the server on the screen.

Mini Socket Server Broadcasting Paribu BTC Data

"use strict";

process.title = 'btc paribu';

var webSocketsServerPort = 1337;

var webSocketServer = require('websocket').server;
var http = require('http');
var axios = require('axios');
var uuid = require('uuid');

axios.defaults.timeout = 180000;

var clients = [];

/**
 * HTTP server
 */
var server = null;

function createServer() {
  server = http.createServer(function (request, response) { });

  server.listen(webSocketsServerPort, function () {
    console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
  });
  var wsServer;

  wsServer = new webSocketServer({
    httpServer: server
  });

  wsServer.on('request', function (request) {
    var connection = request.accept(null, request.origin);
    var _cnnuuid = add_connection(connection);

    connection.on('message', function (message) {
      if (message.type === 'utf8') { // accept only text

      }
    });
    connection.on('close', function (connection) {
      clean_disconnect_cnn();
    });
  });
} // createserver

function add_connection(_cnn) {
  let _cnnuuid = null;

  try {
    _cnnuuid = uuid.v4();
    clients.push({ uuid: _cnnuuid, cnn: _cnn });

    if (clients.length > 60){
      serverreset();
    }
  } catch (error) {
    console.error(error);
  }

  return _cnnuuid;
}

function getData() {
  if (clients.length > 0 || clients.length == 0) {

    axios.get('https://paribu.com/ticker')
      .then(function (response) {
        console.log((new Date()) + " Sended Data (Client : " + clients.length + ")");

        sendData(response);
       
      })
      .catch(function (error) {
        console.log("error https://paribu.com/ticker ");

        setTimeout(() => { 
          getData(); 
        }, 3000);

        const fs = require('fs');
        let tar = new Date().toISOString();
        fs.appendFile("log/log.txt", tar + "\n\r" + JSON.stringify(error) + "\n\r\n\r", function(err) {
          if(err) {
              return console.log(err);
          }
        }); 
      });
  } else {
    setTimeout(() => { getData(); }, 2000);
  }
}

function clean_disconnect_cnn() {
  if (clients.length == 0) return;
  let disconnected = clients.filter(function (e) {
    return !e.cnn.connected;
  });

  if (disconnected.length > 0) {
    clients = clients.filter(function (e) { return e.cnn.connected; });

  }
}

function sendData(_senddata) {
  try {
    if (_senddata != null && _senddata.data != undefined && _senddata.data != null) {
      let jsondata = JSON.stringify(_senddata.data);

      if (clients.length > 0) {
        for (let i = 0; i < clients.length; i++) {
          try {
            if (clients[i].cnn.connected) {
              clients[i].cnn.send(jsondata);
            }
          } catch (error) {
            console.error(error);
          }
        }
      }
    } else {
      console.log("not data received");
    }
  } catch (error) {
    console.log(error);
  }

  setTimeout(() => { getData(); }, 5000);
}

createServer();
getData();

setInterval(() => {
  serverreset();
}, 1000 * 60 * 2); // 2dk da bir restart

function serverreset(){
  try {
    clients.forEach(element => {
      element.cnn.close();
    });
  } catch (error) {}
  
  server.close();
  clients = [];
  console.log("server closed");
  server = null;

  createServer();
}

 

 


  • Web Yazılım
  • Yazılım



Yorumlar
Sende Yorumunu Ekle
Kullanıcı
0 karakter