VDS Sunucu ile WebSocket Sunucusu Nasıl Kurulur?

WebSocket, istemci ve sunucu arasında çift yönlü iletişim sağlar. VDS sunucu üzerinde WebSocket kurarak gerçek zamanlı uygulamalar geliştirebilirsiniz.


1. Node.js ve npm Kurulumu

İlk olarak, Node.js ve npm’yi kurun:

sudo apt update
sudo apt install nodejs npm -y

Kurulumu doğrulamak için:

node -v
npm -v

2. WebSocket Kütüphanesinin Yüklenmesi

WebSocket için ws kütüphanesini yükleyin:

npm install ws

3. WebSocket Sunucusu Oluşturma

Yeni bir dosya oluşturun:

touch server.js
nano server.js

Aşağıdaki kodu ekleyin:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
ws.on('message', (message) => console.log('Mesaj:', message));
ws.send('Hoş geldiniz!');
});

4. Sunucuyu Başlatma

Sunucuyu başlatın:

node server.js

5. İstemciyle Bağlantıyı Test Etme

Yeni bir HTML dosyası oluşturun:

touch index.html
nano index.html

Aşağıdaki kodu yapıştırın:

<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<title>WebSocket Test</title>
</head>
<body>
<script>
const socket = new WebSocket('ws://<sunucu-ip>:8080');
socket.onopen = () => socket.send('Merhaba!');
socket.onmessage = (event) => console.log(event.data);
</script>
</body>
</html>

<sunucu-ip> kısmını sunucunuzun IP adresiyle değiştirin.


6. Güvenlik ve Performans İyileştirmeleri

  • Firewall: 8080 portunu açın:yamlKopyalaDüzenlesudo ufw allow 8080
  • SSL/TLS: Güvenlik için SSL sertifikası kullanın.

Sonuç

Bu adımlarla WebSocket sunucusunu kurarak, gerçek zamanlı uygulamalar geliştirebilirsiniz.

VDS Sunucu Satın Almak İçin : https://www.vps.com.tr/vds-server.php

Vps.com.tr