Mbangun Server dhasar WebSocket karo Node.js

Aplikasi chatting real-time minangka conto sing apik babagan carane nggunakake WebSocket kanggo Node.js nggawe pengalaman pangguna sing interaktif lan nyenengake. Ing artikel iki, kita bakal njelajah carane nggawe real-time aplikasi chatting nggunakake WebSocket lan Node.js.

Langkah 1: Nggawe Lingkungan

Pisanan, priksa manawa sampeyan wis Node.js diinstal ing komputer. Gawe folder anyar kanggo proyek sampeyan lan navigasi menyang folder kasebut nggunakake Terminal utawa Command Prompt.

Langkah 2: Nginstal WebSocket Pustaka

Kaya sadurunge, gunakake perpustakaan "ws" kanggo nginstal WebSocket perpustakaan:

npm install ws

Langkah 3: Nggawe WebSocket Server

Gawe file kanthi jeneng server.js  lan tulis kode ing ngisor iki:

// Import the WebSocket library  
const WebSocket = require('ws');  
  
// Create a WebSocket server  
const server = new WebSocket.Server({ port: 8080 });  
  
// List of connections(clients)  
const clients = new Set();  
  
// Handle new connections  
server.on('connection',(socket) => {  
    console.log('Client connected.');  
  
    // Add connection to the list  
    clients.add(socket);  
  
    // Handle incoming messages from the client  
    socket.on('message',(message) => {  
        // Send the message to all other connections  
        for(const client of clients) {  
            if(client !== socket) {  
                client.send(message);  
            }  
        }  
    });  
  
    // Handle connection close  
    socket.on('close',() => {  
        console.log('Client disconnected.');  
        // Remove the connection from the list  
        clients.delete(socket);  
    });  
});  

Langkah 4: Nggawe Antarmuka Panganggo(Klien)

Gawe file kanthi jeneng index.html lan tulis kode ing ngisor iki:

<!DOCTYPE html>  
<html>  
<head>  
    <title>Real-Time Chat</title>  
</head>  
<body>  
    <input type="text" id="message" placeholder="Type a message">  
    <button onclick="send()">Send</button>  
    <div id="chat"></div>  
      
    <script>  
        const socket = new WebSocket('ws://localhost:8080');  
        socket.onmessage =(event) => {  
            const chat = document.getElementById('chat');  
            chat.innerHTML += '<p>' + event.data + '</p>';  
        };  
  
        function send() {  
            const messageInput = document.getElementById('message');  
            const message = messageInput.value;  
            socket.send(message);  
            messageInput.value = '';  
        }  
    </script>  
</body>  
</html>  

Langkah 5: Mbukak Server lan Mbukak Browser

Ing Terminal, jalanake printah ing ngisor iki kanggo miwiti WebSocket server:

node server.js

Bukak browser web lan navigasi menyang " http://localhost:8080 " kanggo nggunakake real-time aplikasi chatting.

 

Kesimpulan

Sugeng rawuh! Sampeyan wis kasil mbangun real-time aplikasi chatting nggunakake WebSocket lan Node.js. Aplikasi iki ngidini pangguna sesambungan lan ngirim / nampa pesen ing real-time. Sampeyan bisa terus ngembangake lan ngatur aplikasi iki kanggo nggawe macem-macem fitur sing nyenengake!