Communication between Nodejs http server and net server - node.js

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

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

err_EMPTY_RESPONSE (node + express)

I'm trying to learn node.js by writing chat programs. I already got the main functionality, however when I tried to add my CSS file I made some changes to the netcode to try and include static files (line 11) and now the server doesn't send data to the client. Instead, I receive an empty response error. Here is my server code.
var express = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var app = express();
http.listen(3000, function(){
console.log('listening on *:3000');
});
app.use(express.static('public'))
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
//connect
var address = socket.handshake.address;
console.log('connection from ' + address);
io.emit('connection from ' + address);
var user = address;
//bring up to speed
var contents = fs.readFileSync(__dirname + '/log.txt', 'utf8');
io.emit('up2speed', contents);
console.log('bringing ' + user + ' up to speed...');
//change name
socket.on('set_user', function(nick){
console.log('changing ' + user + ' to ' + nick + '...')
user = nick;
})
//message
socket.on('send_mes', function(msg){
console.log(user + ' : ' + msg);
io.emit('send_mes', user + ' : ' + msg)
fs.appendFileSync('log.txt', user + ' : ' + msg + '\n');
});
});
I've tried retracing my steps but that just put me where I started. A page with no CSS.

method client.write() doesn't work on simple server Node.js,

Could anybody say why server doesn't display "hello" from client.write("hello") ?
Thank you a lot!
server:
var net = require('net');
var server = net.createServer(function(client) {console.log('new client s')});
server.listen(2345,function(){console.log('opened server on ',2345)});
client:
var net = require('net');
var client = net.connect({port: 2345, host:'localhost'},function(){
console.log('connected to server!');
client.write("hello");
});
Server is not displaying because you have not handled what to do on recieving data from client :
For server:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 2345;
net.createServer(function(client) {
client.on('data', function(data) {
console.log('DATA ' + client.remoteAddress + ': ' + data);
client.write (data);
});
client.on('close', function(data) {
console.log('CLOSED: ' + client.remoteAddress +' '+ client.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
for client:
var net = require('net');
var client = net.connect(2345,'127.0.0.1',function(){
console.log('connected to server!');
client.write("hello");
});
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 2345;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('Hello');
});

using iojs express and fluent-ffmpeg

i am trying to create a simple io.js that will read an opus file, convert it to mp3, and pass it to a webpage using express. here is what i have tried so far:
var express = require('express');
var ffmpeg = require('fluent-ffmpeg');
var app = express();
var fs = require('fs');
app.get ('/ffmpegTest', function(req,res) {
var stream = fs.createWriteStream('tester.mp3');
ffmpeg('./tester.opus')
.audioCodec('libmp3lame')
.output(stream, {end:true})
// tested to make sure it worked .saveToFile('./testerTEST.mp3')
.on('error', function(err) {
console.log('Processing error! ' + err);
}) ;
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
i also tried this from the website example (this was just a guess)
var command = ffmpeg('./tester.opus')
.audioCodec('libmp3lame')
.on('error', function(err) {
console.log('Processing error! ' + err);
}) ;
var ffstream = command.pipe();
ffstream.on('data', function(chunk) {
console.log('ffmpeg just wrote ' + chunk.length + ' bytes');
});
both of these examples give me "ffmpeg exited with code 1". when i try using "saveToFile" and write a test mp3 file it works fine.
is there a simpler or better way to do this?
here is a working solution based on what user33946 suggested (below). i would still rather use something like fluent-ffmpeg if possible.
var childProcess = require('child_process');
var express = require('express');
var fs = require('fs');
var path = require('path');
'use strict;'
var app = express();
app.get ('/ffmpegTest/:formatType/', function(req, res) {
var formatType = req.params.formatType ;
var inputFile = req.query.inputFile ;
console.log('formatType = ' + formatType);
console.log('inputFile = ' + inputFile);
var cmd = '/usr/local/bin/ffmpeg'
+ ' -i '
+ inputFile
+ ' -f '
+ formatType
+ ( formatType == 'mp3' ? ' -codec:a libmp3lame ' : '' )
+ ' -;'
;
var result = childProcess.exec
( cmd
, { 'encoding' : 'binary
, 'maxBuffer' : 1024 * 500
}
, function (error, stdout, stderr) {
if (error) {
console.log(error.stack);
console.log('Child Process STDERR: ' + stderr);
console.log('Error code: ' + error.code);
console.log('Signal received: ' + error.signal);
} else {
res.setHeader
( 'Content-Disposition'
, 'attachment; filename='
+ path.basename(inputFile, path.extname(inputFile))
+ '.'
+ formatType
);
res.setHeader('Content-Type', 'audio/' + formatType );
res.setHeader('Content-Length', stdout.length );
res.end(new Buffer(stdout, 'binary'));
console.log('result length: ' + stdout.length);
}
}
);
result.on('exit', function (code) {
console.log('Child process exited with exit code ' + code );
});
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

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

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

Resources