Send task from server to clients nodejs

Asked

Viewed 57 times

0

I am using socket.io and making a server and client in nodejs. The communication between them is working. Server receives notification when client connects and disconnects. I am now needing to send server tasks to the client and store these messages in an array by clients

server.js

io.on( 'connection', ( socket ) =>{
console.log( 'Nova conexão, exibindo o ID desse cliente:', socket.id )

if( socket.id )
{
    socket.on('task', ( task ) => {

        let arrTask = [];

        cron.schedule('*/10 * * * * *', () => {
            console.log( task )
        })

        socket.on('disconnect', () => {
            console.log( 'Cliente desconectado' )
        })

    })

}
})

client js.

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

  console.log( "Cliente conectou" );
  socket.emit( 'task', 'Cliente '  + socket.id + ', recebi sua tarefa' );

})

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

  console.log( msg );

});

If anyone can help me I would be grateful. Oh, I’m sorry but I couldn’t get the right code.

  • @Sorack thanks for editing, I was not getting it. I would know help me on this issue of code?

1 answer

0

I don’t think I understand exactly ... but I’m a little confused with your code.

Let’s start from the beginning:

socket.Emit => sends a message

socket.on => keeps listening to the channel and as soon as receiving does something.

on the client side:

socket.on( 'connect', () =>{
  let tarefa = {dados: "fazer algo", tempo: 50, teste: false};
  console.log( "Conectou com o servidor de socket" );
  socket.emit( 'task', tarefa); // emite a tarefa assim que conecta no servidor.
});

socket.on('mensagem-retorno', (msg) => {
  console.log( msg );
});

Already on the server.js

io.on( 'connection', ( socket ) =>{
    console.log( 'Nova conexão, exibindo o ID desse cliente:', socket.id )

    if( socket.id )
    {
        socket.on('task', ( tarefa) => {
            // essa parte de armazenar eu não sei como você irá fazer.
            console.log( tarefa ); // << sua tarefa está aqui. 
            let arrTask = [];



            cron.schedule('*/10 * * * * *', () => {
                console.log( tarefa )
            })

            socket.on('disconnect', () => {
                socket.emit('mensagem-retorno', 'Sua tarefa foi recebida e processada'); // o cliente vai estar observando o "canal" mensagem-retorno
                console.log( 'Cliente desconectado' );
            });

        });

    }
});

Did you understand? if you want to send the message to all clients connected to the server, you should use broadcast.

  • Thanks @Thomaz Diogo Cimin

  • Managed to run smoothly? If you have more doubt comments there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.