Multiple ports node.js application deployment on web/cloud - node.js

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

Related

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

https request from heroku

I am tying to get data from vk.com api via https protocol. like this (api vk docs):
var https = require('https');
https.get('https://api.vk.com/method/users.get?access_token=' + global['access_token'], function (d) {
var chunk = '';
d.on('data', function (data) {
chunk += data;
});
d.on('end', function () {
console.log(chunk);
});
}).on('error', function (e) {
console.error(e);
});
but in heroku logs I see
Error: Protocol:https: not supported.
So, how can I get this data? My app work in http protocol, this is config:
var express = require('express'),
routes = require('./routes');
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.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
Node v0.8.9 added the functionality to make https.get() accept a URL.
Unless you have a very specific reason, use "node": "0.10.x" under engines in package.json.
Also try:
`var options = {
host: 'api.vk.com',
port: 443,
path: '/method/users.get?access_token=' + global['access_token']
};
https.get('options', function(....`

Node.js buffering socket data

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);
});

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.

Socket.io 'Cannot connect'. Client on different domain/port

I'm having trouble connecting to socket.io with the client being located on a different port, on the same machine.
The client is part of a site run on Apache (port 80) and Nodejs is being run on 8585.
Any idea what I'm doing wrong here?
On the client side, I get the 'Unable to connect Socket.IO' message, with no reason.
Server:
var express = require('express'),
connect = require('connect'),
RedisStore = require('connect-redis')(express),
io = require('socket.io').listen(app),
routes = require('./routes'),
request = require('request');
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(express.session({ secret: "secret", store: new RedisStore}));
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());
});
io.set('authorization', function(handshakeData, callback) {
console.log('authorization');
callback(null, true);
});
//Socket IO connection
io.sockets.on('connection', function (socket) {
var session = socket.handshake.session;
console.log(session);
});
app.listen(8585);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
Client: (run from a site on apache and different domain, but same server).
var sio = io.connect('http://localhost:8585');
sio.socket.on('error', function (reason){
console.error('Unable to connect Socket.IO', reason);
});
sio.on('connect', function (){
console.error('successfully established a working connection \o/');
});
Thank you!
Unless you're running the browser on the same computer as the server, "localhost" in your code will refer to the computer running the browser, not the server. DNS lookups for localhost always resolve to the computer doing the lookup. And even if you're accessing the site on the same computer as the server, unless you're accessing it as "localhost", the browser's security policies will prevent you from talking to localhost.

Resources