node.js forward http request from 'net' server to express - node.js

I'm running the flash socket policy server on port 8484. On the same port I need to receive http requests. I'm thinking about checking whether policy-file was requested (inside the if statement below), and if it wasn't - forwarding the http request to another port where express is running (let's say localhost:3000). How can I obtain that?
// flash socket policy server
var file = '/etc/flashpolicy.xml',
host = 'localhost',
port = 8484,
poli = 'something';
var fsps = require('net').createServer(function (stream) {
stream.setEncoding('utf8');
stream.setTimeout(10000);
stream.on('connect', function () {
console.log('Got connection from ' + stream.remoteAddress + '.');
});
stream.on('data', function (data) {
console.log(data);
var test = /^<policy-file-request\/>/;
if (test.test(data)) {
console.log('Good request. Sending file to ' + stream.remoteAddress + '.')
stream.end(poli + '\0');
} else {
console.log('Not a policy file request ' + stream.remoteAddress + '.');
stream.end('HTTP\0');
// FORWARD REQUEST TO localhost:3000 for example //
}
});
stream.on('end', function () {
stream.end();
});
stream.on('timeout', function () {
console.log('Request from ' + stream.remoteAddress + ' timed out.');
stream.end();
});
});
require('fs').readFile(file, 'utf8', function (err, poli) {
if (err) throw err;
fsps.listen(port, host);
console.log('Flash socket policy server running at ' + host + ':' + port + ' and serving ' + file);
});

I solved this problem a while ago, but have forgotten about the question :) The solution was to create a socket which made it possible to send and retrieve data between http express server and tcp flash policy server.
flash policy server:
var file = process.argv[2] || '/etc/flashpolicy.xml',
host = process.argv[3] || 'localhost',
port = process.argv[4] || 8484,
poli = 'flash policy data\n',
net = require('net'),
http = require('http');
var fsps = net.createServer(function (stream) {
stream.setEncoding('utf8');
stream.on('connect', function () {
console.log('Got connection from ' + stream.remoteAddress + '.');
});
stream.on('data', function (data) {
var test = /^<policy-file-request\/>/;
if (test.test(data)) {
console.log('Good request. Sending file to ' + stream.remoteAddress + '.')
stream.end(poli + '\0');
} else {
console.log('Not a policy file request ' + stream.remoteAddress + '.');
var serviceSocket = new net.Socket();
serviceSocket.connect(3000, 'localhost', function () {
console.log('>>>> Data from 8484 to 3000 >>>>\n', data.toString());
serviceSocket.write(data);
});
serviceSocket.on("data", function (received_data) {
console.log('<<<< Data from 3000 to 8484 to client <<<<\n', received_data.toString());
stream.write(received_data);
});
}
});
stream.on('end', function () {
console.log('tcp server disconnected');
});
stream.on('timeout', function () {
console.log('Request from ' + stream.remoteAddress + ' timed out.');
});
});
require('fs').readFile(file, 'utf8', function (err, poli) {
if (err) throw err;
fsps.listen(port, host);
console.log('Flash socket policy server running at ' + host + ':' + port + ' and serving ' + file);
});
sample express server on localhost:3000:
var express = require('express')
, http = require('http')
, path = require('path')
, app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', function(req, res){
res.send('Proper HTTP response');
});
app.post('/', function(req, res){
console.log(req.body);
res.send('Proper HTTP response');
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express HTTP server listening on port ' + app.get('port'));
});

Related

Sockets.io issue: WebSocket is closed before the connection is established

I am currently building a nodejs webrtc video conference, hosted on azure. The program works perfectly fine locally, but when hosted there seems to be an issue with websockets. The client side error is below:
WebSocket connection to '<URL>' failed: WebSocket is closed before the connection is established.
index.js:83 WebSocket connection to 'wss://etuition.azurewebsites.net:8080/socket.io/?EIO=3&transport=websocket' failed: WebSocket is closed before the connection is established.
I have seen other stack overflow posts claiming that this is due to SSL, but site is currently running on HTTPS so this should not be a problem for me. Is it possible that the ws server is insecure even though my http server is secure?
Any other advice on what could be the problem will be greatly appreciated.
Below I have included my server.js code.
Please ask if any more information is needed:
/**
* Server module.
*
*
*/
'use strict';
var environment = process.env.RTC_ENV || 'local';
var debug = require('debug')('expressapp:server');
var express = require('express');
var cors = require('cors');
const http = require('http');
var logger = require('./logger').logger(environment);
var serverPort = normalizePort(process.env.PORT || '8080');
//var serverPort = normalizePort(process.env.PORT || '8080');
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
//var serverPort = process.env.RTC_PORT || 31000
var serverIpAddress = process.env.RTC_IP || 'localhost'
var socketIoServer = 'etuition.azurewebsites.net' + ':' + serverPort;
////////////////////////////////////////////////
// SETUP SERVER
////////////////////////////////////////////////
var app = express();
app.set('port', serverPort);
function redirectSec(req, res, next) {
if (req.headers['x-forwarded-proto'] == 'http') {
var redirect = 'https://' + req.headers.host + req.path;
console.log('Redirect to:' + redirect);
res.redirect(redirect);
} else {
return next();
}
}
app.use(redirectSec);
require('./router')(app, socketIoServer, environment);
// Static content (css, js, .png, etc) is placed in /public
app.use(express.static(__dirname + '/public'));
app.use(cors());
// Location of our views
app.set('views', __dirname + '/views');
// Use ejs as our rendering engine
app.set('view engine', 'ejs');
// Tell Server that we are actually rendering HTML files through EJS.
app.engine('html', require('ejs').renderFile);
const server = http.createServer(app);
server.listen(serverPort);
server.on('listening', onListening);
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
logger.info("Socket IO Address:" + socketIoServer);
logger.info("Server IP Address:" + serverIpAddress);
logger.info('Server running on port ' + serverPort);
}
var io = require('socket.io').listen(server, { log: false, origins: '*:*' });
////////////////////////////////////////////////
// EVENT HANDLERS
////////////////////////////////////////////////
io.sockets.on('connection', function (socket) {
function log() {
var array = [">>> Message from server: "];
for (var i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
socket.on('message', function (message) {
log('Got message: ', message);
logger.info("message: ", message);
socket.broadcast.to(socket.room).emit('message', message);
});
socket.on('create or join', function (message) {
var room = message.room;
socket.room = room;
var participantID = message.from;
configNameSpaceChannel(participantID);
io.of('/').in(room).clients(function (error, clients) {
var numClients = clients.length;
log('Room ' + room + ' has ' + numClients + ' client(s)');
log('Request to create or join room', room);
if (numClients == 0) {
logger.info(participantID + " joined first. Creates room " + room);
socket.join(room);
socket.emit('created', room);
} else {
logger.info(participantID + " joins room " + room);
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room);
}
})
});
// Setup a communication channel (namespace) to communicate with a given participant (participantID)
function configNameSpaceChannel(room) {
var nsp = '/' + room;
var socketNamespace = io.of(nsp);
logger.info('ConfigNameSpaceChannel:' + nsp);
socketNamespace.on('connection', function (socket) {
socket.on('message', function (message) {
// Send message to everyone BUT sender
socket.broadcast.emit('message', message);
});
});
return socketNamespace;
}
});

Socket.io emit not working (by visiting URL)

I am developing an app that gets a signal from external hardware equipment. I catch this signal by redirecting it to a certain URL in my app: '/impulse/:id'.
I am able to catch the signal, but the emit function inside the app.get('/impulse/:id') is not triggering. The console logs are...
How can I make the emit function work?
Below is my server.js script, where I catch all the socket signals and prevent the external call from being redirected to the index page.
...
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const socket = require('socket.io');
app.use(express.static(__dirname + '/public'));
app.use('/api', appRoutes);
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://HERE IS MY DB INFO...', function(err) {
if (err) {
console.log('Not connected to the database: ' + err); // Log to console if unable to connect to database
} else {
console.log('Successfully connected to MongoDB'); // Log to console if able to connect to database
}
});
var server = app.listen(port, function() {
console.log('Running the server on port ' + port); // Listen on configured port
});
var io = socket(server);
io.on('connection', function(socket){
socket.on('join', function(data){
var gameroom = data.gameid;
console.log("joined: " + gameroom)
socket.join(gameroom);
})
//FUNCTION I WANT TO TRIGGER
socket.on('impulse', function(data){
console.log('IMPULSE')
io.emit('impulseReceived', {
})
})
})
//PLACE WHERE I EMIT
app.get('/impulse/:id', function(req, res){
console.log('Impulse Received')
var time = req.query.TIME;
var gameroom = req.params.id;
io.on('connect', function (socket) {
socket.emit('impulse', {
})
})
res.json({ success: true, message: 'received the time!'})
})
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html')); // Set index.html as layout
});
Replace this whole
io.on('connect', function (socket) {
socket.emit('impulse', {
})
}
with this
io.emit('impulse', {})

How to run websocket and client on different ports

I have the following client ( serves the chat interface ) and a websocket, which are connected by the http. Http at the moment runs on the port 8080. So I would like to run the client on one port and the websocket on another, but if I disconnect them by http and of course the websocket doesn´t work on the client.
So is there a way to run them on different ports but still have them connected by the http ?
server:
var express = require('express');
var app = express()
app.use(express.static(__dirname + '/public'));
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs')
var port = 8080;
/************************************************ */
if (process.argv.indexOf('--port') >= 0) {
port = process.argv[process.argv.indexOf('--port') + 1]
}
/************************************************ **/
var sIndexHtmlTemplate = fs.readFileSync(__dirname + '/index1.html', 'utf8');
/************************************************ ***/
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
io.on('connection', function (socket) {
socket.on('chat message', function (msg) {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
});
/************************************************ ***/
http.listen(port, function () {
console.log('listening on *' + port);
});

Socket get net::ERR_CONNECTION_TIMED_OUT when deploy nodejs webapp on iisnode

I am new to nodeJs.Forgive me for asking some silly question.
I am trying to deploy a real-time chatroom webapp on Azure server with iisnode. The webapp works well on localhost, but when I upload it to run on the server, the socket cannot connect from client to server. I am using nodejs+ express + jade.
server.js
var express = require("express"), http = require('http');
var app = express();
var server = http.createServer(app);
var port = process.env.PORT || 3700;
app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
var deployPath = process.env.deployPath || "";
app.get(deployPath+ "/", function(req, res){
res.render("page",{deployPath: deployPath});
});
app.use(deployPath, express.static(__dirname + '/public'));
var io = require('socket.io')(server);
server.listen(port, 'http://visafe-paltform.cloudapp.net');
io.sockets.on('connection', function (socket) {
console("connected");
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
console.log("Listening on port " + port);
Client.js
window.onload = function() {
var messages = [];
var address = window.location.protocol + '//' + window.location.host;
console.log(address);
var details = {
resource: (window.location.pathname.split('/').slice(0, -1).join('/') + '/socket.io').substring(1)
};
console.log(details);
//var socket = io.connect(address, details);
var socket = io.connect('http://visafe-paltform.cloudapp.net:3700');
//var socket = io.connect();
var field = document.getElementById("field");
var sendButton = document.getElementById("send");
var content = document.getElementById("content");
socket.on('message', function (data) {
if(data.message) {
messages.push(data.message);
var html = '';
for(var i=0; i<messages.length; i++) {
html += messages[i] + '<br />';
}
content.innerHTML = html;
} else {
console.log("There is a problem:", data);
}
});
sendButton.onclick = function() {
var text = field.value;
console.log("click:", field.value);
socket.emit('send', { message: text });
};
}
when i try to request the url, it gives me error:
socket.io.js:4948 GET http://visafe-paltform.cloudapp.net:3700/socket.io/?EIO=3&transport=polling&t=LjM71Yc net::ERR_CONNECTION_TIMED_OUT
Can anyone help me? Thanks in advance.
For a classic VM, you should open port 3700 on Azure Endpoint and Windows Firewall.
More information about how to open port on endpoint please refer to this link.
If you want to access your service with Public IP, please ensure your service is listening on 0.0.0.0 and you could telnet 127.0.0.1 3700 successful on your VM.

Communication between Nodejs http server and net server

In here I have a http server and a net server on the same file. The net server connects to Arduino. I want to show the data received from Arduino on the http server website. Also when a button is pressed on the website, I want to send some data through the net server to the arduino. How can I do that.
var http = require("http");
var url = require('url');
var fs = require('fs');
var ip = require('ip');
var net = require('net');
var colors = require('colors');
var formidable = require('formidable');
var HOST = ip.address();//my IP address
var HTTP_PORT = 4321;
var NET_PORT = 1234;
var NAME;
var backButton;
var _p1 = '<form role="form" action="enext" method="post" enctype="multipart/form-data">'
+ '<h1>'
+ '=== Arduino Data Online ==='
+ '</h1><br><h2>'
+ 'Arduino data: ';
var _msg = 'sock data';
var _p2 = '</h2><br><br>'
+ '<h3>'
+ 'Press NEXT after fp success'
+ '</h3><br><b>'
+ '<button type="submit">'
+ 'NEXT'
+ '</button></form>';
//socket
function func(sock) {
console.log(colors.cyan('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort));
// Add a 'data' event handler to this instance of socket
sock.on('data', function (data) {
////========
console.log(data);
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function (data) {
console.log(colors.cyan('CLOSED: ' + sock.remoteAddress + ' ' + sock.remoteNET_PORT));
console.log("");
httpserver.close();
});
sock.on('error', function (data) {
console.log(colors.magenta("clnt error"));
httpserver.close();
});
}
net.createServer(func).listen(NET_PORT, HOST);
console.log(colors.yellow('Server listening on ' + HOST + ':' + NET_PORT));
var httpserver = http.createServer(function (request, response) {
var path = url.parse(request.url).pathname;
console.log('CONNECTED');
console.log(path);
switch (path) {
case '/':
response.writeHead(200, { "Content-Type": "text/html" });
response.write(_p1, "utf8");
response.write(_msg, "utf8");
response.write(_p2, "utf8");
response.end();
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
response.end();
break;
}
});
httpserver.listen(HTTP_PORT, HOST);
console.log('http://Server # ' + HOST + ':' + HTTP_PORT);

Resources