Socket.io is not emitting value - javascript

I am having problem in receiving values emitted by socket.io, I am not getting where is the problem. Here am posting the code please help me to solve the problem.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawnSync = require('child_process').spawnSync;
....
app.post('/loadImage',upload.any(),function(req, res) {
fs.readFile('/home/pathtofile/file.json','utf8',function(err,data){
if(err){
console.log(err);
}else{
//console.log(data);
var precjson = JSON.parse(data);
var loaded_filename = precjson.Filename;
io.emit('emitfilename',{loaded_filename});
}
})
}
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
And here is my code where I am receiving the emitted values:
<script type="text/javascript">
var socket = io.connect('http://localhost:8080');
socket.on('emitfilename',function(data){
//console.log(data);
var li = document.createElement('li');
var filename = document.createElement('h4');
filename.textContent = 'File Name:' + data.filename;
li.appendChild(filename);
document.getElementById('filenameoutput').appendChild(li);
});
</script>
Instead of getting file name , I am getting undefined. Can any one please help me.

You can't use "io" variable to emit data. You can use current socket of the client that just connected to send data :
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Or use io.sockets to emit to all sockets
io.sockets.emit('users_count', clients);
Hope it solve your problem ! Thanks !

Related

How to make the websocket server be at a router?

I'm writing a websocket server using nodejs-ws module, but the server can only be at the root of the server, so how I can make it at a child router like localhost:3000/chat?
I need your help, thanks a lot!
Working example:
var ws = require('ws');
var http = require('http');
var httpServer = http.createServer();
httpServer.listen(3000, 'localhost');
var ws1 = new ws.Server({server:httpServer, path:"/chat"});
ws1.on('connection', function(){
console.log("connection on /chat");
});
var ws2 = new ws.Server({server:httpServer, path:"/notifications"});
ws2.on('connection', function(){
console.log("connection on /notifications");
});
could you please tell me how to use this in express?
To route websockets with Express I'd rather use express-ws-routes
var express = require('express');
var app = require('express-ws-routes')();
app.websocket('/myurl', function(info, cb, next) {
console.log(
'ws req from %s using origin %s',
info.req.originalUrl || info.req.url,
info.origin
);
cb(function(socket) {
socket.send('connected!');
});
});

combining functionality of two Node servers with different initial set up

I have two node servers and I need to combine them so one server has the functionality of both. They were set up a little differently and I'm not sure how to resolve it.
The first server has the require statements at the top, routes in the middle and creates the server at the bottom like this:
var express = require('express');
var routes = require('./routes');
etc..
// middleware
// routes
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The second one looks like this:
var express = require('express')
, app = express()
, server = app.listen(80)
, io = require('socket.io').listen(server)
, fs = require('fs')
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
io.sockets.on('connection', function (socket) {
});
I cut pasted part of it so now the first server script looks (roughly) like this.
// All imports
var express = require('express');
var routes = require('./routes');
var mongoose = require('mongoose');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var multer = require('multer');
var connect = require('connect');
var methodOverride = require('method-override');
var io = require('socket.io');
// middleware
// routes
// trying to make this a route
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Combining the two scripts has resulted in an error listed below at the line listed below.
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot call method 'on' of undefined:
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
I don't understand why I'm getting this error after changing the two require statements and moving the server creation and listening to the bottom of the server. Does anyone know how I can fix this?
You're requiring socket.io, which has a .listen method, not an .on method. Once you call .listen, you'll get back an object that has the .on method you're trying to use.
io = require('socket.io').listen(server);
(You're also missing server, which is created in the second script by calling express().listen(somePortNumberLike80)
You can't just copy and paste code and expect it to work, really.

socket.io connection not heppening

This is first time, I am using socket.io.I stuck at initial stage itself.sorry it's may be simple question.
server side code :
Inside my server.js I written the following code.
var express = require('express')
,io=require('socket.io')
,http = require('http')
var app = express();
server = http.createServer(app);
io = io.listen(server,{ log: false });
Now I trying to make connection inside server.js file,like in the following way.
io.sockets.on('connection', function (socket) {
console.log("This is testing");
io.to(socket.id).emit('notification', 'for your eyes only');
});
client side code :
var socket = io.connect("http://localhost");
socket.on('connect', function () {
console.log("connect")
});
socket.on('notification', function (data) {
console.log(data);
});
I open application in browser, as per my code it suppose to console connect statement but it's not happening.
my server is running on port no :80Where am I did wrong, can anyone help me.
Thanks.
Here is the working code for me in express it may help you.
var express = require('express')
, app = express()
, server = require('http').Server(app)
, io = require('socket.io')(server)
var defaultPort = 6001 ;
server.listen(defaultPort, function() {
console.log('Server Started');
});
io.sockets.once('connection', function(socket) {
return io.sockets.emit('new-data', {
channel: 'stdout',
value: "Your Data Goes Here"
});
socket.on('disconnect', function(){
});
});
On Client Side
<script>
$(function() {
var socket = io.connect('http://localhost'); //if you are trying on server put server url if you are working on local then use localhost
socket.on('new-data', function(data) {
$('#YouDivid').html(data.value);
});
});
</script>

Using Node.js to retrieve data from Redis through an AJAX request

I'm going through a Node, Express, & Socket.io chat tutorial. I decided to use Redis to store the chat history and have successfully set it up so that my information is correctly posting to the database. I am now trying to access that information to use on the client-side (in this case I'm trying to access the list of users currently in the chat so I can show them to the side of the chat). I am using $.getJSON to make a GET request. Right now I have it setup so that the file it tries to access only has this JSON object : {"dog" : "2","cat":"3"} just to test it, and that is working, but I'm not sure where to go from there because anytime I try adding a function into that file, even if I specify to return a JSON object and call that function, the request stops returning the correct information.
For example I tried :
var data = function(){
return {"dog" : "2","cat":"3"}
}
data();
and that doesn't return anything ( I understand that when I make a GET request the function isn't run, but it doesn't even return that text, and if it doesn't run a function than I'm not sure how I can access redis from this file)
Here's what I'm thinking:
var redis = require('redis')
//figure out how to access the redis client that I have at localhost:6379, something like var db = redis.X
//and then call (for example) db.smembers('onlineUsers') and be returned the object which I can iterate through
Here's my relevant code:
server.js:
var jade = require('jade');
var PORT = 8080;
var redis = require('redis');
var db = redis.createClient();
var pub = redis.createClient();
var sub = redis.createClient();
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(PORT, function(){
console.log("Now connected on localhost:" + PORT)
});
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('home');
});
io.sockets.on('connection', function(client){
sub.subscribe("chatting");
sub.on("message", function (channel, message) {
console.log("message received on server from publish");
client.send(message);
});
client.on("sendMessage", function(msg) {
pub.publish("chatting",msg);
});
client.on("setUsername", function(user){
pub.publish("chatting","A new user in connected:" + user);
db.sadd("onlineUsers",user);
}
);
client.on('disconnect', function () {
sub.quit();
pub.publish("chatting","User is disconnected :" + client.id);
});
});
script.js:
$(document).ready( function(){
$client = io.connect();
initialize();
});
var setUsername = function(){
var username = $("#usernameInput").val();
if (username)
{
var user = username;
$client.emit('setUsername', username);
$('#chatControls').show();
$('#usernameInput').hide();
$('#usernameSet').hide();
showCurrentUsers();
}
}
var showCurrentUsers = function(){
$('#list_of_users').empty();
$.getJSON('getusers.js', function(data){
for (var i = 0; i < data.length; i++){
$('list_of_users').append("<li>"+data[i]+"</li>")
}
})
}
var sendMessage = function(){
var msg = $('#messageInput').val();
var username = $("#usernameInput").val();
if (msg)
{
var data = {msg: msg, user: username}
$client.emit('message', data);
addMessage(data);
$('#messageInput').val('');
// populate(username,msg);
}
}
var addMessage = function(data) {
$("#chatEntries").append('<div class="message"><p>' + data.user + ' : ' + data.msg + '</p></div>');
}
// var populate = function(username,msg) {
// var data ;
// }
var initialize = function(){
$("#chatControls").hide();
$("#usernameSet").on('click', setUsername);
$("#submit").on('click',sendMessage);
showCurrentUsers();
}
and right now all that the getusers.js file has in it is:
{"dog" : "2","cat":"3"}
It looks like you're expecting your call to $.getJSON to load and execute the javascript it loads. It doesn't work this way. You need to make a node endpoint (via a route) which renders the JSON. The node endpoint would then do the data manipulation / querying redis:
Node:
In routes.js:
app.get('/chatdata', ChatController.getChatData);
In ChatController.js (manipulate, create the data as you like here)
exports.getChatData = function (req, res) {
var data = function(){
return {"dog" : "2","cat":"3"}
};
res.JSON(data);
};
Front-end
$.getJSON('getChatData', function(data){
//...
})
I think you need to setup a route to handle the GET request that $.getJSON makes, or if getusers.js is in the /public directory, then you need to modify your $.getJSON call as follows:
$.getJSON('http://localhost:8080/public/getusers.js', function(data){
Ok, it looks like it is a problem with your getusers.js file. $.getJSON seems to prefer double quotes. Try formatting it like this:
{
"dog" : "2",
"cat" : "3"
}
Also, try using this to display the data:
$.getJSON('getusers.js', function(data){
var items = [];
$.each( data, function( key, val ) {
items.push("<li id='" + key + "'>" + val +"</li>");
});
$('#list_of_users').append(items.join(""));
});

Javascript create object with data structure like this

I would like to create an object with a similar data structure if possible.
Must I create a new object for every player? Could somebody tell me how?
players
players.name='John'
players.John.age='12'
players.John.adress='London ..'
players.John.telnumber='09876587655'
edit1
Sorry I know this is the basic. I just ask one more question an them i will try learn better javascript. I need to pass data stored in "event" to object."event".id (to be like players.John.id instead players.event.id)
Sorry for my bad english.
// in app.js
var fs = require('fs');
var socketio = require('socket.io');
Tail = require('tail').Tail;
var express = require('express');
var http = require('http');
var colors = require('colors');
var app = express()
, server = require('http').createServer(app)
, io = socketio.listen(server); // socket needs to listen on http server
server.listen(9099);
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('\r\n');
console.log("Express listening on port " + port +'.'.green);
});
// Routing
//app.use(express.static(__dirname));
// usernames which are currently connected to the chat
//var players = [];
var players = {};
io.sockets.on('connection', function(socket) {
// do all of your socket work in here
console.log('\r\n');
console.log("Connection".green);
var sessionid = socket.id;
console.log(sessionid);
// Success! Now listen to messages to be received
socket.on('message',function(event){
console.log('Received message:',event);
});
socket.on('add user',function(event){
console.log('New User:',event);
// we store the username in the socket session for this client
socket.username = event;
// add the client's username to the global list
players.event = {};
players.event.id = sessionid;
//players.John.foo = "yeah"
//players.John.name = "John"
console.log(players);
socket.emit('login', {});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username
});
});
//socket.emit('start', 'newround');
});
edit2
Got it working.
// in app.js
var fs = require('fs');
var socketio = require('socket.io');
Tail = require('tail').Tail;
var express = require('express');
var http = require('http');
var colors = require('colors');
var app = express()
, server = require('http').createServer(app)
, io = socketio.listen(server); // socket needs to listen on http server
server.listen(9099);
app.use(express.static(__dirname + '/public'));
var port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('\r\n');
console.log("Express listening on port " + port +'.'.green);
});
// Routing
//app.use(express.static(__dirname));
// usernames which are currently connected to the chat
//var players = [];
var players = {};
io.sockets.on('connection', function(socket) {
// do all of your socket work in here
console.log('\r\n');
console.log("Connection".green);
var sessionid = socket.id;
console.log(sessionid);
// Success! Now listen to messages to be received
socket.on('message',function(event){
console.log('Received message:',event);
});
socket.on('add user',function(event){
console.log('New User:',event);
// we store the username in the socket session for this client
socket.username = event;
// add the client's username to the global list
players[event] = {};
players[event].id = sessionid;
//players.John.foo = "yeah"
//players.John.name = "John"
console.log(players);
socket.emit('login', {});
// echo globally (all clients) that a person has connected
socket.broadcast.emit('user joined', {
username: socket.username
});
});
//socket.emit('start', 'newround');
});
You're looking for a players object, with individual players referenced by name. So:
var players = {};
players['John'] = {
'age' = 12,
'address' = 'London...',
'telnumber' = '09876587655'
};
You can also access "John" as players.John, but that gets tricky if any of the names contain spaces, etc.
Similarly, the player attributes can be accessed either via:
players.John['age'] = 13;
or
players.John.age = 13;
var name = "John";
var players = {};
players[name] = {};
players[name].age = '12';
players[name].address = "address";
players[name].telnumber = "tel";

Categories

Resources