NodeJS/SocketIO Socket will not emit - javascript

I'm trying to 'emit' data to the server, but nothing is happening.
The console says that I've connected, but it won't log anything whenever
I try to emit the specific command.
Clientside (JQuery/JS):
var ip = "";
$.ajax({
url : "../host",
success : function(result){
ip = result;
}
});
var socket = io.connect(ip);
socket = io('/admin');
socket.on('add_task', function(name, event, command, args) {
AddTask(name, event, command, args); //I get this data from the server
});
socket.on('remove_task', function(name) {
DeleteTask(name); //I get this data from the server.
});
$("#addTask").click(function() {
var args = ["add", $("#nameData").val(), $("#eventData").val(), $("#commandData").val(), $("#argData").val()];
socket.emit("task", args); //This won't emit anything.
$("#add-modal").modal("hide");
});
Serverside (NodeJS):
admin.on('connection', function(socket) {
console.log("An admin has connected."); //This logs
task.get().forEach(function(tsk) {
var tdata = tsk.split(':');
admin.emit('add_task', tdata[0], tdata[1], tdata[2], tdata[3]); //This sends
});
admin.on('task', function(args) {
console.log(args); //This doesn't log
});
});

You need to listen for the event on the connected socket, like so:
admin.on('connection', function(socket) {
socket.on('task', function(args) {
console.log(args);
});
});
This is because the event comes from the connected socket, otherwise socket.io would have no way of knowing which socket the event came from and the event's associated data would be meaningless.

Related

Page doesn't automatically update when socket.io receive

I want to page update when new socket.io data appear.
I have a server -> client comunication:
Server code (the n var is the message)
io2.on('connection', function(socket2) {
socket2.on('live', function(data2) {
console.log('status from live client:', data2);
socket2.emit('live', n);
});
});
Live page code:
var socket = io.connect('http://localhost:3002');
socket.emit('live', 'live client is connected');
socket.on('live', function(data) {
//alert(data)
document.getElementById("demo").innerHTML = data;
});
The socket works fine because when I send the data and I refresh the page it show what I want. The problem is that I want to see the updated message without manual refresh.
Thanks!
The scope for n is undefined in the first function, so the receiving function doesn't have anything to show.
You'll need to define n in the original emitting function.
You need to emit the event from server side to the client side and then catch data there
var server = app.listen(3000);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('event', function(data) {
var n = data.message;
io.sockets.emit('event', message);
});
And then on frontend in live page you write this
var n = <%-JSON.stringify(v1)%>;
var socket = io.connect('http://localhost:3000');
socket.on('event', (data)=>{
console.log(data)
});

Why socket.io returns multiple times for an event

I just started picking up socket.io. I'm trying to use it in angular.js and everything works fine. However, it keeps returning multiple times
in my controller.js
socketio.emit('GameOver',$scope.currentPlayer.Name);
socketio.on('GameOverEmit',function(data){
if(data === $rootScope.user.user_name){
var result = {
opponent : rdyplayers.user_name,
result : "won"
};
// keep getting multiple result
console.log(result);
}else{
var result = {
opponent : rdyplayers.user_name,
result : "lose"
};
// keep getting multiple result
console.log(result);
}
});
In my server.js
io.sockets.on('connection', function (client) {
​
client.user_name = user.user_name;
​
//Useful to know when someone connects
console.log('\t socket.io:: player ' + client.user_name + ' connected');
// playerturn
client.on('PlayerTurn',function(data){
io.emit('PlayerTurnEmit',data);
​
});
// game over
client.on('GameOver',function(data){
io.emit('GameOverEmit',data);
​
});
// button disabled
client.on('PlayerButtonDisabled',function(data){
io.emit('PlayerButtonDisabledEmit',data);
});
//When this client disconnects
client.on('disconnect', function () {
//Useful to know when someone disconnects
console.log('\t socket.io:: client disconnected ' + client.user_name );
io.emit("disconnected",client.user_name);
}); //client.on disconnect
​
}); //io.sockets.on connection
Am I using socket.io in the correct way? In order to broadcast the data to everyone I just pass the data into an emit and take the data broadcast it by using on like pass the data to server and pass it back to the front-end?
For broadcast use socket.broadcast.emit()
I don't find any socket disconnection listen event code in your client side code.. try adding socketio.disconnect for disconnection for client side
And also add a listener to the socket disconnection emit event from server to client ..on the client side by adding socketio.on('disconnect', function(){do something})
it caused by controller.js, whenever i revisit the page it will establish a new socket so what i did is whenever a user leave or close the tab it removes all the listener.
i ended up solving it by adding getsocket in my service.js
ttt.factory('socketio', ['$rootScope', function ($rootScope) {
'use strict';
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
});
},
getSocket: function() {
return socket;
}
};
}]);
and in my controller.js i do
$scope.$on('$destroy', function (event) {
socketio.getSocket().removeAllListeners();
});

I am receiving a message in node.js and the object socket is undefined

I have the following code:
function Socket(io, playGame, mapper) {
io.on('connection', function (socket) {
// message handler for the chat message
socket.on('sendChat', function (data) {
console.log(socket);
console.log(data);
console.log('recieved chat');
var connectedPlayer = playGame.findConnectedPlayer(socket);
if (!connectedPlayer)
return;
var connectedGame = playGame.findConnectedGame(socket, connectedPlayer.gameId);
if (!connectedGame)
return;
// send update game with players properly ordered
for (socketIndex in this.sockets) {
var socket = this.sockets[socketIndex];
// send the new data to each player
socket.socket.emit('chatUpdate', { chatText: data.chat });
}
});
// message handler for join game message
socket.on('joinGame', function (data) {
console.log('recieved join:', JSON.stringify(data));
if (!playGame.newConnectedPlayer(socket, data))
return;
...
In the method for sendChat, socket is undefined. In the method for joinGame, socket is defined. I have tried several ideas, but the problem persists. Any help would be appreciated.
You'll have to rename one of the 2 socket variables -- either the parameter for 'connection' or the var in the loop:
io.on('connection', function (socket) {
for (socketIndex in this.sockets) {
var socket = this.sockets[socketIndex];
The var is shadowing the parameter, rendering the parameter inaccessible.
This happens in part because the var socket doesn't only exist within the for loop. JavaScript vars are function-scoped and their declarations are hoisted to the top of the function, as in:
socket.on('sendChat', function (data) {
var connectedPlayer, connectedGame, socket; // each initially `undefined`
console.log(socket);
// ...
for (socketIndex in this.sockets) {
socket = this.sockets[socketIndex];
// ...
});
And, having the same exact name, at most only one of them can be reached from a particular function.
Also note that the for loop and var socket aren't really necessary.
You can use the Socket.IO Server's own .emit() method to send a message to all clients.
io.emit('chatUpdate', { chatText: data.chat });

Node JS push server send/receive

I am trying to set up a node js server to do push notifications to my browser app. I have a basic example working, but I am wondering how to send data up to the server from the client on handshake.
I Need to send to the server something like a user id, so when a notification comes in for them, it can be routed back to the user.
my server looks something like this
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs');
app.listen(8000);
function handler ( req, res ) {
res.writeHead( 200 );
res.end('node working');
};
io.sockets.on( 'connection', function ( socket ) {
socket.volatile.emit( 'notification' , "blah" );
});
and my client looks something like this
var socket = io.connect('http://localhost:8000');
socket.on('notification', function (data) {
//prints data here
});
In socket.io, the emit is essentially like any other event handler (e.g. jQuery's .on('click'...)); you declare the event and send the data. On the server, you add the .on('event', ...) to catch the request and process it.
The socket.io front page shows this example for the server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
And this for the client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
It sounds like the part you're looking for is the socket.emit portion.
I have done this sort of thing in the past by setting a cookie on the client (which you're probably doing anyway), and then using socket.io's authorization event. You can use this event to decide whether to even accept the socket connection to the user in the first place.
io.configure(function () {
io.set('authorization', function (handshakeData, callback) {
var cookie = handshakeData.headers.cookie;
// parse the cookie to get user data...
// second argument to the callback decides whether to authorize the client
callback(null, true);
});
});
See more documentation here: https://github.com/LearnBoost/socket.io/wiki/Authorizing
Note that handshakeData.headers.cookie is just a string literal representation of the cookie, so you'll have to do your own parsing.

JavaScript callbacks function object

i try to learn node.js and try to create a new TCP Server connection. The code
var server = require('net').createServer(function(socket) {
console.log('new connection');
socket.setEncoding('utf8');
socket.write("Hello! You can start typing. Type 'quit' to exit.\n");
socket.on('data', function(data) {
console.log('got:', data.toString());
if (data.trim().toLowerCase() === 'quit') {
socket.write('Bye bye!');
return socket.end();
}
socket.write(data);
});
socket.on('end', function() {
console.log('Client connection ended');
});
}).listen(4001);
look at the callback function, after then, they call listen method. What is this for kind of object.
What it basically says is:
function myHandler(socket) {
// everything up to socket.on('end')
}
var server = require('net').createServer(myHandler);
server.listen(4001);
So it's just creating a socket server with a handler function, and then make the server listen to port 4001.

Categories