Question

When I create a HTTP server with Node.js and handle the file path in a specific way I usually use the callback like this:

var http = require('http').createServer(function (req, res) {
 var request = url.parse(req.url, false);
 var filename = request.pathname;
 if (filename == "/") filename = "/index.html";
 /* Append the frontend folder */
 filename = 'frontend' + filename;
 fs.readFile(filename, function (err, data) {
    /* Any error on reading the file? */
    if (err) {
        if (err.errno == 34) // File not found
            res.writeHead(404);
        else res.writeHead(500);
        res.end();
        return;
    }
    res.writeHead(200);
    res.write(data);
    res.end();
 });
}).listen(8080);

Now, when I create a net server I don't get my function (req, res){}. Now when I create my server with net. The only callback element that I have is a socket, which I definitely need for my app. and it looks like this:

var server = net.createServer(function(socket) {})

So I guess my question is, if I want to specify the path file of when I client connect can I do directly with net, or do I need something else?

Was it helpful?

Solution

After doing some reading and asking around I realize that net is only to establish a tcp server that deals directly with a port. There for coming up with a client side is impossible.

I was using the net server to receive information from a Fio V3 through a WiFly. and then send the data to a client side. I came up with a solution that perhaps not the best seems to work.

Since I wanted to send the information to a client through a web socket connection, I ended up with three servers. Here is the code:

var http = require('http');
var fs = require('fs');
var path = require('path');
var url = require('url');
var net = require('net');
var sensorData;
var message = {
  "data": ''
}
var newValue,
  oldValue,
  diff;
//Settings
var HTTP_PORT = 9000;
var NET_PORT = 9001;
var WS_PORT = 9002;
//Server
var mimeTypes = {
  "html": "text/html",
  "jpeg": "image/jpeg",
  "jpg": "image/jpeg",
  "png": "image/png",
  "js": "text/javascript",
  "css": "text/css"
};
http.createServer(function (req, res) {
  var fileToLoad;
  if (req.url == '/') {
    fileToLoad = 'index.html';
   } else {
    fileToLoad = url.parse(req.url).pathname.substr(1);
  }
  console.log('[HTTP] :: Loading :: ' + 'frontend/' + fileToLoad);
  var fileBytes;
  var httpStatusCode = 200;
  fs.exists('frontend/' + fileToLoad, function (doesItExist) {
    if (!doesItExist) {
      console.log('[HTTP] :: Error loading :: ' + 'frontend/' + fileToLoad);
      httpStatusCode = 404;
    }
    var fileBytes = fs.readFileSync('frontend/' + fileToLoad);
    var mimeType = mimeTypes[path.extname(fileToLoad).split('.')[1]];
    res.writeHead(httpStatusCode, {
      'Content-type': mimeType
    });
    res.end(fileBytes);
  });
}).listen(HTTP_PORT);
var socket;
var clients = [];
var server = net.createServer(function (socket) {
  socket.name = socket.remoteAddress + ":" + socket.remotePort;
  clients.push(socket);
  socket.write("HTTP/1.1 101", function () {
    console.log('[CONN] New connection: ' + socket.name + ', total clients: ' +     clients.length);
  });
  socket.setEncoding('utf8');
  socket.on('error', function (data) {
    console.log(data);
  });
  socket.on('end', function () {
    console.log('[END] Disconnection: ' + socket.name + ', total clients: ' + clients.length);
  });
  socket.on('data', function (data) {
    console.log('[RECV from ' + socket.remoteAddress + "] " + data);
    oldValue = newValue;
    newValue = data;
    diff = Math.abs(newValue) - Math.abs(oldValue);
    console.log(Math.abs(newValue) + '-' + Math.abs(oldValue));
    message.data = Math.abs(diff);
    console.log('[SAVED] ' + message.data);
  });
});
server.listen(NET_PORT, function () {
  console.log("[INIT] Server running on port", NET_PORT);
});
var WebSocketServer = require('ws').Server,
  wss = new WebSocketServer({
    port: WS_PORT
  });
wss.on('connection', function (ws) {
  // ws.send(JSON.stringify(message));
  setInterval(function () {
    updateXData(ws)
  }, 500);
});

function updateXData(ws) {
  var newMessage = {
    "data": ""
  }

Hope it does make sense, If someone comes up with a better solution, pls share :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top