में प्रसारण और WebSocket एकीकरण Node.js

डेटा प्रसारित करना और एकीकृत करना WebSocket वास्तविक समय अनुप्रयोगों के निर्माण के दो महत्वपूर्ण पहलू हैं Node.js । WebSocket इस लेख में, हम यह पता लगाएंगे कि एक इंटरैक्टिव और उत्तरदायी उपयोगकर्ता अनुभव बनाने के लिए डेटा को कैसे प्रसारित किया जाए और कैसे एकीकृत किया जाए।

चरण 1: सर्वर से डेटा प्रसारित करना

सर्वर से क्लाइंट कनेक्शन पर डेटा प्रसारित करने के लिए, आप broadcast सभी कनेक्शनों पर संदेश भेजने या send किसी विशिष्ट कनेक्शन पर संदेश भेजने जैसी विधियों का उपयोग कर सकते हैं। यहां सर्वर से डेटा प्रसारित करने का एक उदाहरण दिया गया है:

// ... Initialize WebSocket server  
  
// Broadcast data to all connections  
function broadcast(message) {  
    for(const client of clients) {  
        client.send(message);  
    }  
}  
  
// Handle new connections  
server.on('connection',(socket) => {  
    // Add connection to the list  
    clients.add(socket);  
  
    // Handle incoming messages from the client  
    socket.on('message',(message) => {  
        // Broadcast the message to all other connections  
        broadcast(message);  
    });  
  
    // Handle connection close  
    socket.on('close',() => {  
        // Remove the connection from the list  
        clients.delete(socket);  
    });  
});  

चरण 2: अनुप्रयोगों WebSocket में एकीकृत करना Node.js

WebSocket किसी एप्लिकेशन में एकीकृत करने के लिए Node.js, आपको WebSocket अपने जावास्क्रिप्ट कोड में एक कनेक्शन स्थापित करना होगा। यहां WebSocket आपके एप्लिकेशन के क्लाइंट-साइड में एकीकृत करने का एक उदाहरण दिया गया है:

// Initialize WebSocket connection from the client  
const socket = new WebSocket('ws://localhost:8080');  
  
// Handle incoming messages from the server  
socket.onmessage =(event) => {  
    const message = event.data;  
    // Process the received message from the server  
    console.log('Received message:', message);  
};  
  
// Send a message from the client to the server  
function sendMessage() {  
    const messageInput = document.getElementById('messageInput');  
    const message = messageInput.value;  
    socket.send(message);  
    messageInput.value = '';  
}  

 

निष्कर्ष

डेटा प्रसारित करके और एकीकृत करके WebSocket, Node.js आप इंटरैक्टिव और उत्तरदायी वास्तविक समय एप्लिकेशन बना सकते हैं। यह उपयोगकर्ता के अनुभवों को बढ़ाता है और क्लाइंट और सर्वर अनुप्रयोगों के बीच वास्तविक समय की बातचीत को सक्षम बनाता है।