Programu real-time ya gumzo ni mfano bora wa jinsi ya kutumia WebSocket ili Node.js kuunda uzoefu shirikishi na unaovutia wa mtumiaji. Katika makala haya, tutachunguza jinsi ya kuunda real-time programu ya gumzo kwa kutumia WebSocket na Node.js.
Hatua ya 1: Kuweka Mazingira
Kwanza, hakikisha kuwa umesakinisha Node.js kwenye kompyuta yako. Unda folda mpya ya mradi wako na uingie ndani yake kwa kutumia Terminal au Command Prompt.
Hatua ya 2: Kusakinisha WebSocket Maktaba
Kama hapo awali, tumia maktaba ya "ws" kusakinisha WebSocket maktaba:
npm install ws
Hatua ya 3: Kuunda WebSocket Seva
Unda faili iliyopewa jina server.js
na uandike nambari ifuatayo:
// 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);
});
});
Hatua ya 4: Kuunda Kiolesura cha Mtumiaji(Mteja)
Unda faili iliyopewa jina index.html
na uandike nambari ifuatayo:
<!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>
Hatua ya 5: Kuendesha Seva na Kufungua Kivinjari
Kwenye Terminal, endesha amri ifuatayo ili kuanza WebSocket seva:
node server.js
Fungua kivinjari cha wavuti na uende kwenye " http://localhost:8080 " ili kutumia real-time programu ya gumzo.
Hitimisho
Hongera! Umefanikiwa kuunda real-time programu ya gumzo kwa kutumia WebSocket na Node.js. Programu hii inaruhusu watumiaji kuingiliana na kutuma/kupokea ujumbe katika real-time. Unaweza kuendelea kupanua na kubinafsisha programu hii ili kuunda vipengele mbalimbali vya kusisimua!