Node.js buffering socket data - node.js

I am using current versions of all things node.js, express.js, socket.io etc ... I am trying to connect to a server who's sole purpose in life is just spew text and in turn send it to web client connected via socket.io. The text is nothing more character strings with standard line endings and the max data rate is something on the order of 1024bytes/sec. My code, the core bits, is something like this
var express = require('express')
, app = express()
, routes = require('./routes')
, user = require('./routes/user')
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, path = require('path')
, dataSourcePort = 5000
, host = "10.0.1.32"
, dataStream = require('net').createConnection(dataSourcePort, host);
dataStream.setEncoding('utf8');
io.sockets.on('connection', function (socket) {
dataStream.on('data',function(data){
socket.emit("stuff",data);
});
});
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
This works all fine and dandy but, every once in a while it just hangs, as in the data stops going out to the clients. I assume a buffer gets stuffed somewhere along the line but, not sure. Is there a better way to do this and avoid the stuffing part?

The main issue I see is that you never unbind your data handler, so as people connect and disconnect, you will accumulate data listeners and memory usage, and waste resources trying to send data to disconnected sockets.
io.sockets.on('connection', function (socket) {
function ondata(data){
socket.emit("stuff",data);
}
function ondisconnect(){
dataStream.off('data', ondata);
socket.off('disconnect', ondisconnect);
}
dataStream.on('data', ondata);
socket.on('disconnect', ondisconnect);
});

Related

Multiple ports node.js application deployment on web/cloud

I have an electronic board, which collects data from sensors and I hope to send it to an web service, which then does some processing and sends the results to an website, when URL is entered. I use multiple ports for this. One port listens for UDP connection and other port is for HTTP. The code works fine on my local machine. Here is the code
var net = require('net')
,dgram = require('dgram')
,express = require('express')
,io = require('socket.io')
,routes = require('./routes')
,http = require('http')
,fs = require('fs');
var app = module.exports = express.createServer();
var HOST = '192.168.0.132'
var PORT = 1337
var datarr = []
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {layout:false, pretty:true});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
//ROUTES
app.get('/',routes.index);
//UDP Server
var decoder = new (require('string_decoder').StringDecoder)('utf-8')
var buffer = '';
var server = dgram.createSocket('udp4');
server.on('listening',function() {
console.log('Listening');
});
server.on('message', function(data,rinfo) {
console.log(decoder.write(data));
io.sockets.emit('data',decoder.write(data));
});
server.on('close', function(data) {
console.log('closed');
});
server.bind(1337,'192.168.0.132');
//UDP server ends
var io=require('socket.io').listen(app);
app.listen(1185);
io.sockets.on('connection',function (socket) {
console.log('Hello Got a connection');
});
console.log("server listening");
I know it can't be hosted on heroku, because it allows only one port.
What are my options?
1)According to some answers on this website, websockets. But i have no idea on how to set up websocket between udp and http server. Any links to websites/github would be very helful.
2)Hosting services which allow multiple ports. Are there any which provide this service? Links to documentations will be appreciated.
Thanks in advance.
You can do some thing like this
var port = process.env.PORT || 1185;
and then use this port variable as
app.listen(port);
every time when you need to run on different port just use
PORT = node app.js

Accessing the Backbone model.save() POST payload in the node-express backend

I have written a code snippet using backbone which POST's data to the urlRoute .
(function(){
"use strict"
window.Course = Backbone.Model.extend({
defaults:{
title:''
},
urlRoot:"courses/"
});
var courses = new Course({title:"Sending a Post request to the node-express backend,but how to access this in the backend"});
courses.save();
})();
I have used node.js - express framework in the backend ,i want to know how to retrieve the value of the title attribute using the app.post('/courses',function(req,res){}) method .
This is the node.js backend ,The control comes to the app.post method , but just want ot how to the access the model value in the posted data .
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.post('/courses',function(req,res) {
console.log('Request successfully recieved');
console.log("how do i get the posted data here !!");
});
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
You can find your request data in req.body (more on that http://expressjs.com/api.html#req.body).
In your case you can do like this:
app.post('/courses',function(req,res) {
console.log(req.body.title);
});

backbone.js sending "OPTIONS" as a restful request

Backbone talking to node/express running locally os x 10.6.8. Trying to populate a clientside backbone model with fetch. Thinking I have fetch wrong. Most of app_stuff.js is cut-and-paste. Curious why node/express sees the request as OPTIONS instead of GET (or POST?) and if I have the terminology right. I think I can make it work like this but would rather pay the dues for some best practices while still an absolute newb.
backbone
(function($) {
var Stuff = Backbone.Model.extend({
});
var Collec = Backbone.Collection.extend({
model: Stuff,
url: 'http://localhost:3000/stuff'
});
var nstuff = new Collec;
nstuff.fetch(
{ data: $.param({ name: "helloworld"}) }
);
})(jQuery);
app_stuff.js
var express = require('express')
, routes = require('./routes')
, stuff = require('./routes/stuff')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/stuff', stuff.index);
app.options('/stuff', function() { console.log("stuffed"); });
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
terminal output
$ node timeline/app_stuff.js
Express server listening on port 3000
stuffed

Express Node.js not responding on live server

i have written a simple hello world program in express node.js and when i call it through Curl it's response is correct i.e it displays Hello world on the console but when i call the url from browser i get could not connect error.Here is my code:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3039);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/partner', function(req, res){
res.send('Hello World');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
You have either a DNS issue or a Firewall issue.
Perhaps this answer will help you.
Which cloud service you are using for node.js .share url of this page

Nodejs simple socket.io example not working

I've the following Server Side Code:
var express = require('express')
, http = require('http')
, routes = require('./routes')
, io = require('socket.io')
, factory = require('./serverfactory.js');
var app = express();
var server = app.listen(3000);
io = io.listen(server);
io.sockets.on('connection',function(socket){
console.log('new user');
socket.emit('hail','mysimplemsg');
socket.on('customevent',function(msg){
console.log(msg);
});
});
//var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', routes.index);
And this is the client side :
var socket = io.connect('http://localhost:3000');
socket.emit('customevent','work');
socket.on('hail',function(msg){
console.log(msg);
});
I am expecting that my git console outputs new user (which it does) then it should output work (which it does not) then i get a msg in my browser console mysimplemsg (which it does not).
Whats going on why the event at server side that is customevent is not called and why the event at the client side that is hail is not called ?
I believe the issue is that you are emitting customevent from the client before you are connected. Try adding a connect handler and moving your client side emit into it:
var socket = io.connect('http://localhost:3000');
socket.on('hail',function(msg){
console.log(msg);
});
socket.on('connect',function(){
console.log('connected to socket.io server');
socket.emit('customevent','work');
});
If the connect handler is not hit then verify that you are referencing the client side socket.io javascript library correctly (jade syntax):
script(type='text/javascript',src='/socket.io/socket.io.js')
Finally figured it out.
It was working fine on opera but not on chrome and firefox. I found this link in which the guy says to insert this code snippet on the server side.
io.configure('development', function(){
io.set('transports', ['xhr-polling']);
});
It's working fine now.

Resources