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

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

Related

api route not working over https

I have a node server running on port 3000 to serve api request.
this works fine...
http://www.skoolaide.com:3000/api/accounts
this does not.
https://www.skoolaide.com:3000/api/accounts
Can someone tell me why? If you go to https://www.skoolaide.com, the ssl cert is configured correctly, but do I need to do something on the node side?
this is my server js file. Please note: is only runs the middleware(api) on port 3000. For some reason I cannot access the middleware via https...
'use strict';
var express = require('express');
var router = express.Router();
var app = express();
var http = require('http');
var open = require('open');
var cors = require('cors');
var path = require('path');
var morgan = require('morgan');
var errorhandler = require('errorhandler');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var config = require('./config/config');
var jwt = require('jsonwebtoken');
var compression = require('compression');
var runMiddleware = require('run-middleware')(app);
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var multer = require('multer');
var node_xj = require("xls-to-json");
var moment = require('moment');
var async = require('async');
var btoa = require('btoa');
var sharp = require('sharp');
var students = require("./middleware/students.api");
var accounts = require("./middleware/accounts.api");
var messages = require("./middleware/messages.api");
var advocates = require("./middleware/advocates.api");
var authenticate = require("./middleware/authenticate.api");
var email = require("./middleware/email.api");
var text = require("./middleware/text.api");
var colleges = require("./middleware/colleges.api");
var amazon = require("./middleware/amazon.api");
var rewards = require("./middleware/rewards.api");
var files = require("./middleware/files.api");
var validations = require("./middleware/validations.api");
var points = require("./middleware/points.api");
var notifications = require("./middleware/notifications.api");
var notificationsMap = require("./middleware/notificationsMap.api");
var trivia = require("./middleware/trivia.api");
var tasks = require("./middleware/rewardgoals.api");
var classes = require("./middleware/classes.api");
var connections = require("./middleware/connections.api");
var badges = require("./middleware/badges.api");
var fixpasswords = require("./middleware/fixpasswords.api");
var Files = require('./models/files');
mongoose.connect(config.database);
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose disconnected on app termination');
process.exit(0);
});
});
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true
}));
app.set('uploads', path.join(__dirname, 'uploads'));
app.get("/uploads/*", function (req, res, next) {
res.sendFile(__dirname + req.url);
});
var whitelist = ['https://www.skoolaide.com', 'https://skoolaide.com'];
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.headers['origin']) !== -1) {
corsOptions = { origin: true, credentials: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false, credentials: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use(cors(corsOptionsDelegate));
//this is used because the body parser removes undefined values from the database.
app.set('json replacer', function (key, value) {
// undefined values are set to `null`
if (typeof value === "undefined") {
return null;
}
return value;
});
app.use(multer({
dest: './uploads/',
rename: function (fieldname, filename) {
return filename.replace(/\W+/g, '-').toLowerCase() + Date.now()
},
onFileUploadStart: function (file) {
//console.log(file.fieldname + ' is starting ...')
},
onFileUploadData: function (file, data) {
//console.log(data.length + ' of ' + file.fieldname + ' arrived')
},
onFileUploadComplete: function (file) {
//console.log(file.fieldname + ' uploaded to ' + file.path)
}
}).any());
// "files" should be the same name as what's coming from the field name on the client side.
app.post("/api/upload", function (req, res) {
//console.log(req.files[0].mimetype)
fs.readFile(req.files[0].path, function (err, data) {
var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
var readPath = "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
if(req.files[0].mimetype.indexOf('image') > -1){
sharp(data)
.rotate()
.resize(800, 800)
.max()
.toFile(newPath, function(err, info){
var file = new Files();
file.owner = req.headers.account_id || null;
file.classId = req.body.classId || null;
file.rewardGoalId = req.body.rewardGoalId || null;
file.avatarId = req.body.avatarId || null;
file.mimeType = req.files[0].mimetype || null;
file.originalName = req.files[0].originalname || null;
file.path = readPath;
file.save(function (err, newFile) {
if (err) {
res.send(err);
} else {
res.send({ success: true, data: newFile }).end();
}
});
});
} else{
//not an image file...
var newPath = __dirname + "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
//console.log('Writing file: ', newPath);
fs.writeFile(newPath, data, function (err) {
var readPath = "/uploads/" + req.headers["account_id"] + '_' + moment().format('MM_DD_YYYY_HH-mm-ss') + '_' + req.files[0].originalname.replace(/[^a-zA-Z0-9.]/g, '_');
//console.log(readPath)
var file = new Files();
file.owner = req.headers.account_id || null;
file.classId = req.body.classId || null;
file.rewardGoalId = req.body.rewardGoalId || null;
file.profileId = req.body.profileId || null;
file.mimeType = req.files[0].mimetype || null;
file.originalName = req.files[0].originalname || null;
file.path = readPath;
file.save(function (err, newFile) {
if (err) {
res.send(err);
} else {
res.send({ success: true, data: newFile }).end();
}
});
});
}
});
});
app.use(express.static('www'))
var a = ['/'];
//all get requests resolve to index.
app.get(a, function (req, res) {
console.log('This is a test', req.originalUrl, req.url);
res.setHeader('Cache-Control', 'private, no-cache, no-store, must-revalidate');
res.setHeader('Expires', '-1');
res.setHeader('Pragma', 'no-cache');
res.setHeader('X-UA-Compatible', 'IE=Edge,chrome=1');
res.setHeader('Judson', 'Rocks!');
if (req.originalUrl == '/') {
res.sendFile('www/index.html', {root: __dirname});
}
});
app.set("superSecret", config.secret)
//var upload = require("./middleware/upload.api");
app.use('/api', router);
app.use('/api/students', students);
app.use('/api/accounts', accounts);
app.use('/api/messages', messages);
app.use('/api/advocates', advocates);
app.use('/api/authenticate', authenticate);
app.use('/api/email', email);
app.use('/api/text', text);
app.use('/api/colleges', colleges);
app.use('/api/amazon', amazon);
app.use('/api/rewards', rewards);
app.use('/api/files', files);
app.use('/api/validate', validations);
app.use('/api/points', points);
app.use('/api/notifications', notifications);
app.use('/api/notificationsMap', notificationsMap);
app.use('/api/trivia', trivia);
app.use('/api/rewardgoals', tasks);
app.use('/api/classes', classes);
app.use('/api/badges', badges);
app.use('/api/connections', connections);
app.use('/api/fixpasswords', fixpasswords);
/**SERVER*************************************/
// all environments
app.set('port', process.env.PORT || 3000);
app.engine('html', require('ejs').renderFile);
// express/connect middleware
app.use(morgan('dev'));
app.use(compression()); //use compression
// development only
if ('development' === app.get('env')) {
app.use(errorhandler());
}
/**END SERVER*************************************/
var cluster = require('cluster');
if (cluster.isMaster) {
var numWorkers = require('os').cpus().length;
console.log('Master cluster setting up ' + numWorkers + ' workers...');
for (var i = 0; i < numWorkers; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log('Worker ' + worker.process.pid + ' is online');
});
cluster.on('exit', function (worker, code, signal) {
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal);
console.log('Starting a new worker');
cluster.fork();
});
} else {
app.listen(app.get('port'),
function () {
console.log('myApp server listening on port ' + app.get('port'));
});
}
Your code only starts an HTTP server. This line:
app.listen(app.get('port'))
starts only an http server. If you want support for HTTPS, you have to also start an HTTPS server and you have to start it on a different port. The express doc for app.listen() shows you how to do that and it's basicaly like this:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
where options contains your SSL certificates and where you fill in the desired port numbers for your http server and your https server.
If you were operating under the illusion that you don't need a port number in the browser in order to access both an http and https server, that's because the browser fills in a default port number for you. If you just type an http URL, it uses port 80. If you type an https URL with no port, it uses port 443. If you're not on those two specific ports, you have to specify the desired port in the browser URL. In either case, you need a separate server on separate ports for both http and https.
Use var https = require("https"); not
Var http = require ("http");

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

Express and Cluster node modules in the same app

I am creating an app that allows users to upload files in their browsers to a server.
I started it by typing express in the folder of my project. With that express created all the folders and such. It created a bin folder containing a www file that starts a lot of stuff for us like the ports.
At first i only had one core so i was doing it like so:
var express = require('express');
var multer = require('multer');
var app = express();
var done = false;
var fileSize = 0;
app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename){
return filename;
},
onFileUploadStart: function(file){
console.log(file.originalname + ' is starting...');
},
onFileUploadComplete: function(file){
console.log(file.fieldname + ' uploaded to ' + file.path);
done = true;
},
onFileUploadData: function(file, data){
fileSize += data.length;
console.log("FileUpload " + fileSize);
}
}));
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
app.post('/upload/', function(request, response){
console.log(request.body);
if (done == true)
response.end('file uploaded');
});
module.exports = app;
Eventually i needed to user a machine with several cores in order to be able to respond to more client requests. So I am trying to use the cluster module.
I changed the code accordingly:
var cluster = require('cluster');
if(cluster.isMaster){
var numCPUS = require('os').cpus().length;
for(var i=0; i<numCPUS; i++)
cluster.fork();
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
cluster.on('online', function(worker) {
console.log('worker ' + worker.process.pid + ' started');
});
}else{
var express = require('express');
var multer = require('multer');
var app = express();
var done = false;
var fileSize = 0;
app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename){
return filename;
},
onFileUploadStart: function(file){
console.log(file.originalname + ' is starting...');
},
onFileUploadComplete: function(file){
console.log(file.fieldname + ' uploaded to ' + file.path);
done = true;
},
onFileUploadData: function(file, data){
fileSize += data.length;
console.log("FileUpload " + fileSize);
}
}));
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
app.post('/upload/', function(request, response){
console.log(request.body);
if (done == true)
response.end('file uploaded');
});
module.exports = app;
}
The problem is that when i do this i am getting the following error in the console:
Run: node ./bin/www
Result:
app.set('port', port);
TypeERror: Cannot call method 'set' of undefined at Object.<anonymous>
This happens since i placed the entire code inside the forked childs of the master. Anyone knows why this happens and how i can fix it?
EDIT:
In here you can see the bin/www file where the port and some other configurations are set:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('dropbox:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}

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