socket.emit is not working under socket.on - node.js

I am sending data from client to server like
socket.emit('event1', data);
this data is received by server perfectly like
socket.on('event1', function (data){
console.log(data);
});
but when i am sending data from server to client under this socket.on event none of emit event is not working only socket.broadcast.emit is emitting data to client.js
socket.on('event1', function (data){
socket.to(data.room).emit('event2', data); // not working
io.in(data.room).emit('event2', data); // not working
io.sockets.in(data.room).emit('event2', data); // not working
socket.emit('event2', data); // not working
socket.broadcast.to(data.room).emit('event2', data); // not working
socket.broadcast.emit('event2', data); // working
});

The code examples you have shared are missing the comma operator ,, which is used to separate function arguments or other terms in a statement or expression.
Here is every example you submitted, with the comma operator included:
socket.emit('event1', data);
socket.on('event1', function (data) {
console.log(data);
});
socket.on('event1', function (data) {
socket.to(data.room).emit('event2', data); // not working
io.in(data.room).emit('event2', data); // not working
io.sockets.in(data.room).emit('event2', data); // not working
socket.emit('event2', data); // not working
socket.broadcast.to(data.room).emit('event2', data); // not working
socket.broadcast.emit('event2', data); // working
});

Related

Node.js emit not working on specific socket.on

I'm trying to send news to my client. On connect, it works great, but for some reason on broadcast2 it wont get any response client sided, even know its the same piece of code, and even that broadcast2's console.log is working.
Q: How can i make sure broadcast2 emit will work?
This works:
socket.on('message', function (data) {
console.log('message gotten');
socket.emit('news', { message: 'xxxx' });
});
this wont work:
socket.on('broadcast2', function (data) {
console.log("broadcast revieced");
socket.emit('news', { message: 'xxxx' });
});
this is node.js response:
total code in node.js
socket.on('message', function (data) {
console.log('message gotten');
});
socket.on('another-message', function (data) {
socket.emit('not-news', { hello: 'world' });
});
socket.on('broadcast2', function (data) {
console.log("broadcast revieced");
socket.emit('news', { message: 'xxxx' });
});
and this on the client side:
var socket = io.connect('mysite:8080');
function sender() {
console.log('sending tester');
socket.emit('sendertester', 2);
}
socket.on('connect',function(){
});
socket.on('tester', function(msg){
console.log("callback");
});
socket.on('news', function(message) {
console.log("INCOMMING NEWS");
console.log(message);
});
UPDATE 1:
The broadcast2 socket, sent by PHP:
function broadcast($message,$broadcast = 'broadcast2') {
$client = new Client(new Version1X('myurlhidden:8080'));
$client->initialize();
$client->emit($broadcast, ['message' => $message]);
$client->close();
}
UPDATE 2:
**Question two: Cause my broadcast2 is sent before the client sided is loaded, and then the client connects to the node, could that be the cause?
But in the same time, im already preloading the class that holds the broadcast2 emitter.
Using codeigniter framework.**
UPDATE 3
I was trying to check my theory on update 2, by having two users logged in, while user one trying to perform the trigger. user two gets no output, so i suppose that theory is busted.
The server cannot send a message to any socket before it is connected. You have to wait until you have something listening to receive what you are sending.
I wouldn't call close after the emit either, as you may close the connection before the client has received the message, emit doesn't wait for the client to receive the data before returning its asynchronous.
Instead let the clients close the connections when they terminate.

Client is trying to get data with Socket.io but doesn't seem to connect

I have set up sockets on my client and server, but I can't seem to get my data to come into my client. It seems they are connecting properly, I just can't get any data to come through. There are no error messages either.
Here is my server code:
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('custom-message', function () {
console.log("Hitting messages socket");
Message.find(function(err, messages){
if(err){
socket.emit('custom-message', err)
} else {
socket.emit('custom-message', messages);
}
})
});
});
Here is the function in the client that connects to the socket:
loadMessagesFromServer: function(){
console.log("About to load messages")
socket.on('custom-message', function(msg){
console.log("connected in client", msg)
});
},
Like I said it is a pretty simple example, I just can't seem to get the data in loadMessagesFromServer .. And there are no erros, the only way I have been debugging is trying different things..
You are listening on the event messages. So you need to emit the same event not socket.emit('messages: err', err). Try with socket.emit("messages", error). Moreover, in your server-side code, you need first to receive a message event and only then your socket will emit the messages. Remove the socket.on(custom-messages). Why do you need it?
Server-side code
io.on('connection', function (socket) {
/* Here a client connection is established. The on("connection")
* event will be triggered as many times as`io.connect("the-uri")`
* is triggered (and succeeded) in the client`
*/
// Listening for the post event
socket.on("post", function(messages){
console.log("client posted data:", messages)
// Find messages and emit result
Message.find(function(err, messages){
if(err){
socket.emit('error', err)
} else {
socket.emit("message", messages);
}
});
});
});
Client-side code
registerOnMessageFromServerListener: function(){
socket.on("message", function(msg){
console.log("received message:", msg);
});
registerOnErrorFromServerListener: function(){
socket.on("error", function(error){
console.log("an error occured:", error);
});
registerOnMessageFromServerListener();
registerOnErrorFromServerListener();
socket.emit("post", "a-message");
Also make sure that you call the loadMessagesFromServer before you establish the socket connection

why emit not working inside socket

I am trying to send an event to socket inside the socket for example
io.on('connection', function (socket) {
socket.emit("connected", {msg: 1});
socket.on('funcb', function (data) {
console.log('funca sent following data');
console.log(data);
});
socket.on('funca', function (data) {
console.log(data);
socket.emit('funcb', data);
});
});
funca is called from client/browser and it try to call the funcb but func b not working any ideas?
To explain what #bolav said with code:
Client side:
socket.emit("connected", {msg: 1});
socket.on('funcb', function (data) {
console.log('funcb from server sent following data');
console.log(data);
});
socket.on('funca', function (data) {
console.log(data);
socket.emit('funcb', data);
});
Server Side:
socket.on('funcb', function (data) {
console.log('funca from client side sent following data');
console.log(data);
socket.emit("funcb", data);
});
Might be the "emit" is just sending event back to client (browser) not socket itself, so it is unable to catch event 'funcb'
socket.emit('funcb', data) sent from the client will not invoke the socket.on('funcb') listener on the client. It will emit to the other side and invoke the socket.on listener on the server.

Data from .json in socket.io

I have a socket.io connection running with
Client
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
And server
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
var url = 'pathtojson';
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', url);
socket.on('my other event', function (data) {
console.log(data, 'server');
});
});
This is just an example from socket.io. I want to send json data to the client whenever it is updated.
But where do I start ?
You need to have an event fire whenever the data you're interested in updating has changed, and then you need to have the client listen for that event and respond as desired.
You don't really give a context other than "send json data to the client whenever it is updated", so assuming that you are in whatever process is updating your JSON on the server:
if (req.url === '/endpoint') {
yourJSON.foo = 'bar';
// doing whatever you're interested in to the JSON
socket.emit('JSON changed', yourJSON);
//an event is defined by the first argument,
//a value is passed with it as the second
}
NB: Getting more fancy/thoughtful with this means changing your JSON in such a manner that the socket only emits in response to the data change (event, callback, etc). Explicating this pattern is perhaps outside the scope of the question.
Then on the client, you want to define a function to handle those changes:
socket.on('JSON changed', updateFunction);
//where updateFunction is a function you define
//that is expecting arguments that match the output
//from the connected socket.emit event
function updateFunction(newJSON) {
//do whatever with new JSON data
}
This is assuming there is some external endpoint being accessed to update JSON; having it come from a client over socket.io would simply involve defining another event, but this time having it emit from the client, and be listened to by the server.

Socket.io emit callback not firing on server side?

My server emits events properly, but the emit callback never works. In the following, nothing is logged on my console:
Server:
io.sockets.emit('delete hint', {id: id}, function(data){
console.log('callback');
});
Client:
socket.on('delete hint', function(data){
// display a message before deleting
$('#' + data.id).fadeOut(function(){
$(this).remove();
});
});
I've also tried the client side code as function(data, fn) in case the callback needed to be included on the receiving function.
I'm using windows and my command prompt shows the following when socket.io is emitting the event:
websocket writing 5:::{"name":"delete hint", "args":[{"id":"1"}, null]}
I can't figure out what the problem is, what am I doing wrong?
A callback is executed on the sender computer when the receiver computer calls it
Have a look at this code:
Server:
io.sockets.on('connection', connectionFunc);
function connectionFunc (socket) {
socket.emit('delete hint', "data for client", callThis);
}
//this function is executed when client calls it
function callThis (dataFromClient){
console.log("Call back fired: " + dataFromClient);
}
Client:
socket.on('delete hint', function(data, callback) {
console.log("i received: "+ data);
// call back will fire only when u the next line runs
callback("the callThis function on server will run");
});
You can do this the opposite way.
You need to call the callback.
socket.on('delete hint', function(data, cb){
// display a message before deleting
$('#' + data.id).fadeOut(function(){
$(this).remove();
cb(null, 'done');
});
});

Resources