Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is .on function of socket in tcp connection in Node Js

I have a quick question. Can anyone explain this

socket.on("message",function(message){})

I am trying to connect to TCP server on node.js

server.on('connection',function(socket){
        socket.on('message',function(message){
                console.log("got the message");
                socket.sendEndMessage("hello");
            }
        );
    } );

I need to know when socket.on("message",function(message){}) will be called.

like image 895
Aqeel Raza Avatar asked Jan 01 '26 14:01

Aqeel Raza


1 Answers

socket.on("message",function(message){}) will be called when a socket connected to the server emits a 'message' event:

socket.emit('message', { /* an object to be sent */ });

Using socket.on method, allows you to manage how a custom or built-in received message event will be handled. If you're sending different kind of messages through the server, lets say, requestsStats and requestUsersList message types, you'll be emitting messages like

socket.emit('requestStats', { filter: statsFilter });
socket.emit('requestUsersList', { filter: userAccessLevel });

you'll need to process them on the server (or clients) using:

socket.on('requestStats', function(message){ // process message content });

and

socket.on('requestUsersList', function(message) { // process message content });

Basically, you can define custom events/messages to be sent through web sockets.

like image 192
adonike Avatar answered Jan 03 '26 05:01

adonike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!