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

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.

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.

Related

Why don't I see a response from socket.io-client with node.js?

var io = require('socket.io-client'),
socket = io.connect('targeturl', {
port: 8080
});
socket.on('connect', function () {
console.log("socket connected"); //this is printed.
});
socket.emit('list', {"user":'username',"token": 'mytoken'});
socket.on('message', function(data){
console.log(data);
});
socket.on('error', function(data){
console.log(data); //nothing is printed
});
I see the message 'socket connected' when running this from node.js on the command line but I don't see a response from the 'list' call.
Note that this is a specific question about using socket-io-client from Node.js as a command line application.
I have verified using curl that I can reach the socket server which is REMOTE i.e I do not have the server code but I know that it uses socket.io.
I'm no expert on the matter, but it appears you're attempting to emit the message before the connection is established. (This stuff is asynchronous after all.)
Try moving the emit call inside of the handler for the 'connect' event, to ensure that it happens afterward.

nodejs socket emit return undefined

I am trying to send to clients whenever a new connection issued.
My server side javascripts is :
var clients = 0;
io.sockets.on('connection', function (socket) {
clients ++;
console.log(clients);
socket.broadcast.emit('connect',socket.clients);
}
and my client side js to handle:
socket.on('connect', function (data) {
console.log('on'+data);});
the output is undefined (on undefined)
Where 's things wrong?
socket.broadcast.emit('connect',socket.clients);
^^^^^^^^^^^^^^ this should be 'clients'
Also, connect is a pre-defined event with socket.io, so you shouldn't reuse it or it might give unexpected results.
FWIW: socket.broadcast.emit will send a message to all connections except the current one. If that's not what you want (you want the message to be sent to all connections), use io.sockets.emit instead).

How to be sure that message via socket.io has been received to the client?

How to check that message sent with socket.io library has been received to the client.
Is there special method for it in socket.io?
Thanks for your answers!
You should use the callback parameter while defining the event handler.
A typical implementation would be as follows:
Client side
var socket = io.connect('http://localhost');
socket.emit('set', 'is_it_ok', function (response) {
console.log(response);
});
Server side
io.sockets.on('connection', function (socket) {
socket.on('set', function (status, callback) {
console.log(status);
callback('ok');
});
});
Now check the console on the server side. It should display 'is_it_ok'. Next check console on client side. It should display 'ok'. That's the confirmation message.
Update
A socket.io connection is essentially persistent. The following in-built functions let you take action based on the state of the connection.
socket.on('disconnect', function() {} ); // wait for reconnect
socket.on('reconnect', function() {} ); // connection restored
socket.on('reconnecting', function(nextRetry) {} ); //trying to reconnect
socket.on('reconnect_failed', function() { console.log("Reconnect failed"); });
Using the callback option shown above is effectively a combination of the following two steps:
socket.emit('callback', 'ok') // happens immediately
and on the client side
socket.on('callback', function(data) {
console.log(data);
});
So you don't need to use a timer. The callback runs immediately except if the connection has any of the following states - 'disconnect', 'reconnecting', 'reconnect_failed'.
You can use the socket.io's acknowledgements.
Quote from the socket.io documentation:
Sometimes, you might want to get a callback when the client confirmed
the message reception.
To do this, simply pass a function as the last parameter of .send or
.emit. What's more, when you use .emit, the acknowledgement is
done by you, which means you can also pass data along.
On the client side simply emit the event with your data, the function will be called whenever the server responds to your event:
client.emit("someEvent", {property:value}, function (data) {
if (data.error)
console.log('Something went wrong on the server');
if (data.ok)
console.log('Event was processed successfully');
});
On the server side you get called with the data and the callback handle to send the response:
socket.on('someEvent', function (data, callback) {
// do some work with the data
if (err) {
callback({error:'someErrorCode', msg:'Some message'});
return;
}
callback({ok:true});
});
When you add a function as the last parameter of .send() or .emit() method calls, this function is called when the other party receives the message.
socket.send('hi', function() {
// if we are here, our salutation has been received by the other party.
});

NodeJS email proxy

I am trying to proxy emails via NodeJS in order to do very custom processing on outgoing emails on our test server.
This is what I have:
var net = require('net');
var server = net.createServer({allowHalfOpen: true}, function(socket) {
console.log('New connection established.');
socket.setEncoding('utf8');
socket.on('data', function(data) {
console.log(data);
});
socket.on('end', function() {
console.log('Connection closing.');
});
socket.resume();
});
server.listen(25);
It does not yet process the emails, because it simply doesn't even work. I get the connection established message in console every time I send an email, but the data event never gets fired. I'm not sure if it's that the data already came before I bound the event listener, or whether I'm supposed to talk to the client first (HELO?).
I'm trying to access the email contents, basically.

Socket.io with Cluster: iterating over all open connections

I'm running Socket.io multi-threaded with the native cluster functionality provided by Node.js v0.6.0 and later (with RedisStore).
For every new change in state, the server iterates over each connection and sends a message if appropriate. Note: this isn't "broadcasting" to all connections, it's comparing server data with data the client sent on connection to decide whether to send the server data to that particular client. Consider this code sample:
io.sockets.clients().forEach(function (socket) {
socket.get('subscription', function (err, message) {
if(message.someProperty === someServerData) {
socket.emit('position', someServerData);
}
});
This worked fine when there was only one process, but now, the client receives a message for each Node process (ie. if there are 8 Node process running, all clients receive the messages 8 times).
I understand why the issue arises, but I'm not sure of a fix. How can I assign a 1-to-1 relation from one process to only on client. Perhaps something using NODE_WORKER_ID of Cluster?
This previous SO question seems somewhat related, although I'm not sure it's helpful.
This seems like a pretty common request. Surely, I must be missing something?
So if I get this straight you need to emit custom events from the server. You can do that by creating your own custom EventEmitter and triggering events on that emitter, for example:
var io = require('socket.io').listen(80);
events = require('events'),
customEventEmitter = new events.EventEmitter();
io.sockets.on('connection', function (socket) {
// here you handle what happens on the 'positionUpdate' event
// which will be triggered by the server later on
eventEmitter.on('positionUpdate', function (data) {
// here you have a function that checks if a condition between
// the socket connected and your data set as a param is met
if (condition(data,socket)) {
// send a message to each connected socket
// if the condition is met
socket.emit('the new position is...');
}
});
});
// sometime in the future the server will emit one or more positionUpdate events
customEventEmitter.emit('positionUpdate', data);
Another solution would be to have those users join the 'AWE150', so only they will receive updates for 'AWE150', like so:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
if (client_is_interested_in_AWE) { socket.join('AWE150'); }
io.sockets.in('AWE150').emit('new position here');
});
Resources:
http://spiritconsulting.com.ar/fedex/2010/11/events-with-jquery-nodejs-and-socket-io/

Categories

Resources