Watsawa da WebSocket Haɗin kai a cikin Node.js

Bayanan watsa shirye-shirye da haɗawa WebSocket abubuwa ne masu mahimmanci guda biyu na gina aikace-aikacen lokaci-lokaci tare da Node.js. A cikin wannan labarin, za mu bincika yadda ake watsa bayanai da haɗawa WebSocket don ƙirƙirar ƙwarewar mai amfani mai ma'amala da amsawa.

Mataki 1: Watsa Labarai daga Sabar

Don watsa bayanai daga uwar garken zuwa haɗin gwiwar abokin ciniki, zaku iya amfani da hanyoyi kamar broadcast aika saƙonni zuwa duk haɗin gwiwa ko send aika saƙo zuwa takamaiman haɗi. Ga misalin watsa bayanai daga uwar garken:

// ... 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);  
    });  
});  

Mataki 2: Haɗin kai WebSocket cikin Node.js Aikace-aikace

Don haɗawa WebSocket cikin Node.js aikace-aikacen, kuna buƙatar kafa WebSocket haɗi a lambar JavaScript ɗin ku. Ga misali na haɗawa WebSocket cikin abokin ciniki-bangaren aikace-aikacenku:

// 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 = '';  
}  

 

Kammalawa

Ta hanyar watsa bayanai da haɗawa WebSocket a cikin Node.js, za ku iya gina aikace-aikacen mu'amala da amsawa na ainihi. Wannan yana haɓaka ƙwarewar mai amfani kuma yana ba da damar hulɗar lokaci tsakanin abokin ciniki da aikace-aikacen uwar garke.