Socket.io

 Socket.io: Socket.io is a library that enables real-time, bidirectional communication between clients and servers. It provides an easy-to-use API for handling WebSockets and other real-time protocols. Here's an example of how to use Socket.io to send and receive messages in a Node.js application:

javascript


const app = require('express')();

const http = require('http').createServer(app);

const io = require('socket.io')(http);


app.get('/', (req, res) => {

  res.sendFile(__dirname + '/index.html');

});


io.on('connection', (socket) => {

  console.log('a user connected');


  socket.on('chat message', (msg) => {

    console.log('message: ' + msg);

    io.emit('chat message', msg);

  });


  socket.on('disconnect', () => {

    console.log('user disconnected');

  });

});


http.listen(3000, () => {

  console.log('listening on *:3000');

});

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...