I have a following NodeJS server file that is supposed to handle following JSON Message:
If received message as key, send some response.
If received app as key, send some DLL to the client.
Now I am interested in handling multiple clients that will, for this case, send only message as Key in JSON.
Here is the code:
var net = require('net');
var fs = require('fs');
var util = require('util');
var server = net.createServer(function(c) { //'connection' listener
console.log('client connected');
c.on('end', function() {
console.log('client disconnected');
});
c.on('data', function(data) {
var json = JSON.parse(data.toString());
if(json.heartbeat){
if(json.first_fetch === "1"){
c.write("{\"config_changed\":\"true\",\"config\":\"This is some config\"}"); // JSON Message here
}
else{
c.write("{\"config_changed\":\"false\"}");
}
}
else if(json.message){
c.write("{\"success\":\"true\"}");
}
else if(json.app){
fs.exists('apps/'+ json.app + ".dll", function (exists) {
util.debug(exists ? "it's there" : "Its not there");
});
var stats = fs.statSync('apps/'+ json.app + ".dll")
var fileSizeInBytes = stats["size"]
var message = json.app + "\n" + fileSizeInBytes + "\n";
c.write(message);
fs.open('apps/'+ json.app + ".dll","r", function(status, fd){
console.log(fd);
var read_bytes = 0;
var fileStream = fs.createReadStream('apps/'+ json.app + ".dll");
fileStream.on('data',function(chunk){
c.write(chunk);
});
})
}
else
{
c.write("{\"some\":\"error\"}");
}
});
c.on('error', function (e) {
console.log(e);
});
// c.pipe(c);
});
server.listen(1936, function() { //'listening' listener
console.log('server bound');
});
My client will send message as {"message":"This is message"}, and server will send {"success":"true"}. I received following benchmark of the server I created:
One client sent 200000 message in 7 seconds.
Two clients, each sent message in 13/14 seconds.
Three clients, each sent message in 17/17/16 seconds.
The time for each client reduces significantly when they are sending message to one server. I tried to run multiple server at once, but it gave:
events.js:85
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at exports._errnoException (util.js:746:11)
at Server._listen2 (net.js:1156:14)
at listen (net.js:1182:10)
at Server.listen (net.js:1267:5)
at Object.<anonymous> (C:\Users\Dell\Desktop\nodeserver\server.js:54:8)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
If I want to get the performance of 200K in 7 seconds for each of clients, how am I to proceed. I want to run multiple instance of servers, with a load balancer to improve the server efficiency. I am using Windows.
try to use node.js Cluster module for this
https://nodejs.org/api/cluster.html
different nodejs instances can't share same port
another approach is to use external load balancer, nginx for example
http://nginx.org/en/docs/http/load_balancing.html
Related
I'm trying to use named pipes in my application. The problem is when I try to connect to the named pipe before the server is running, I get the following error:
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ENOENT \\?\pipe\\testpipe
at Object.exports._errnoException (util.js:870:11)
at exports._exceptionWithHostPort (util.js:893:20)
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1062:14)
How can I check if the pipe exists before attempting to connect to it?
Note: Wrapping my connect code in a try-catch doesn't prevent the error.
Here is my code:
var net = require('net');
var addr = '\\\\?\\pipe\\testpipe';
var client = net.createConnection({ path: addr }, function() {
console.log("Connected");
client.on('data', function(data) {
console.log("Recieved: " + data);
});
client.on('error', function(){
console.log(arguments);
});
}.bind(this));
Using the domain module prevents a fatal error. The following code can be used to safely run the connect code.
Not what I was hoping for, but the closed solution since there have been no answers.
var net = require('net');
var domain = require('domain');
var addr = '\\\\?\\pipe\\testpipe';
var d = domain.create();
d.on('error', function(err) {
console.error(err);
});
d.run(function() {
var client = net.createConnection({ path: addr }, function() {
console.log("Connected");
client.on('data', function(data) {
console.log("Recieved: " + data);
});
client.on('error', function(){
console.log(arguments);
});
}.bind(this));
});
make the socket, then listen for an error event, then call connect and it won't be thrown: https://nodejs.org/api/net.html#net_event_error_1
So I 100% copy pasted a code from the link below and I get the error below. I have installed all the dependencies required. I have used socket.io previously without problems, but never socket.io.users. The goal is to identify each PC as user.
var chatUsers = socketUsers.Users.of('/chat'); //
^
TypeError: Object #<Users> has no method 'of'
at Object.<anonymous> (/var/www/100moneta/components_not_larval/socket-user.js:16:35)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketUsers = require('socket.io.users');
socketUsers.Session(app);//IMPORTANT
var rootIo = require('socket.io')(server); //default '/' as namespace.
var chatIo = rootIo.of('/chat');
var rootUsers = socketUsers.Users; /* default '/' as namespace. Each namespace has IT's OWN users object list,
but the Id of a user of any other namespace may has the same value if request comes from the same client-machine-user.
This makes easy to keep a kind of synchronization between all users of all different namespaces. */
var chatUsers = socketUsers.Users.of('/chat'); //
rootIo.use(socketUsers.Middleware());//IMPORTANT but no errors if you want to skip it for a io.of(namespace) that you don't want the socket.io.users' support.
chatUsers.use(socketUsers.Middleware());
chatUsers.on('connected',function(user){
console.log(user.id + ' has connected to the CHAT');
user.set('username', 'username setted by server side'); /*at the store property you can store any type of properties
and objects you want to share between your user's sockets. */
user.socket.on('any event', function(data){ //user.socket is the current socket, to get all connected sockets from this user, use: user.sockets
});
chatIo.emit('set username',user.get('username')); //or user.store.username
});
rootUsers.on('connected',function(user){
console.log('User has connected with ID: '+ user.id);
});
rootUsers.on('connection',function(user){
console.log('Socket ID: '+user.socket.id+' is user with ID: '+user.id);
});
rootUsers.on('disconnected',function(user){
console.log('User with ID: '+user.id+'is gone away :(');
});
//You can still use the io.on events, but the execution is after connected and connection of the 'users' and 'chatUsers', no matter the order.
rootIo.on('connection',function(socket){
console.log('IO DEBUG: Socket '+ socket.id+ ' is ready \n');
});
Link with the code and tutorial: https://www.npmjs.com/package/socket.io.users
All,
I have a simple Express web server on Windows Node. I can't work out how to capture the error if I'm trying to start the server on the same port as another instance of Express already running. The error middleware won't capture it and the usual .on("error", function ()....) doesn't work either, and the whole Node application bombs - I want to capture it gracefully.
Here is the code:
var express = require('express');
var compression = require('compression')
var app = express();
var __dirname = ""
app.use(compression({ threshold: 512 }));
var oneYear = 86400000 * 365;
app.enable('etag')
app.use(express.static(__dirname + '../../HAWebClient', { maxAge: oneYear }));
app.use(function (err, req, res, next) {
if (!err) return next();
console.log('<-------Error Occured ----->');
res.send(500, JSON.stringify(err, ['stack', 'message']));
});
app.on("error", function (err) {
status("SYSTEM/HTTP", "Error with the web server: " + err);
// Do stuff with error
});
app.listen(80);
and I get
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:904:11)
at Server._listen2 (net.js:1042:14)
at listen (net.js:1064:10)
at Server.listen (net.js:1138:5)
at Function.app.listen (C:\Users\deandob\Documents\GitHub\PluginMgr\PluginMgr\node_modules\express\lib\application.js:546:24)
at webSvr (C:\Users\deandob\Documents\GitHub\PluginMgr\PluginMgr\PlugMgr.js:298:9)
at Object.<anonymous> (C:\Users\deandob\Documents\GitHub\PluginMgr\PluginMgr\PlugMgr.js:271:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
Press any key to continue...
Don't want to capture this in Node's global error handler (which loses error context) - this error should be able to be captured by app.on("error,....) but I'm obviously missing something here. Thanks for the input!
When the port is already in use, app.listen(80); will throw an exception asynchronously (the exception you see in your error log) if you don't have an error handler on the server. The server, in this case, is the return value from app.listen(), not the app object which is why you attempt at handling the error was not working.
Rather than let that exception go to the system which will shut-down your app, you can catch the error and prevent the exception like this:
var server = app.listen(8080);
server.on('error', function(e) {
console.log(e);
// put your code here
});
And, then decide what to do in the error handler. I have tested this solution in a sample server and it does work.
FYI, the relevant documentation is on the socket object here: https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback
I am trying to create a simple server and a simple client with node.js using http module. Server is working fine but client is not. Please help me to find the bug...
Server Is :
var server = require('http').createServer();
server.on('request', function(req, res){
res.end("hello, world");
});
server.listen(4000);
Client Is :
var options = {
host : 'localhost',
port : 4000,
method : 'GET',
path " '/'
};
require('http').request(options, function(res){
console.log(require('util').inspect(res));
res.on('data', function(data){
console.log(data);
});
I am running them in different terminal windows as node server.js & node client.js.
I am getting below mentioned error on the client.js running terminal after around 10 mins.
events.js:72
throw er; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1473:15)
at Socket.socketOnEnd [as onend] (http.js:1569:23)
at Socket.g (events.js:175:14)
at Socket.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
Thanks !
The request() method of the HTTP library will not automatically end requests, therefore they stay open, and time out. Instead, you should either end the request using req.end(), or use the get() method, which will do so automatically.
var http = require('http');
var req = http.request(options, function(res) {
// handle the resposne
});
req.end();
Or:
http.get(options, function(res) {
// handle the resposne
});
I'm trying this code:
var connect = require("connect");
var io = require("socket.io");
var spawn = require("child_process").spawn;
var server = connect.createServer(
connect.favicon(),
connect.logger(),
connect.staticProvider(__dirname + '/public')
);
server.listen(8000);
var socket = io.listen(server, {flashPolicyServer: false});
var tail = spawn("tail", ["-f", "./nohup.out"]);
tail.stdout.on("data", function(data) {
socket.broadcast(data.toString("utf8"));
});
But when I try to run this I got an error:
Nathan-Camposs-MacBook-Pro:log Nathan$ node app.js
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object function createServer() {
if ('object' == typeof arguments[0]) {
return new HTTPSServer(arguments[0], Array.prototype.slice.call(arguments, 1));
} else {
return new HTTPServer(Array.prototype.slice.call(arguments));
}
} has no method 'staticProvider'
at Object.<anonymous> (/Users/Nathan/Sites/log/app.js:8:10)
at Module._compile (module.js:407:26)
at Object..js (module.js:413:10)
at Module.load (module.js:339:31)
at Function._load (module.js:298:12)
at Array.<anonymous> (module.js:426:10)
at EventEmitter._tickCallback (node.js:126:26)
Nathan-Camposs-MacBook-Pro:log Nathan$
I don't really know the connect library. But this documentation says, that it's static not staticProvider (in the version 1.0).
So your server creating part should be:
var server = connect.createServer(
connect.favicon(),
connect.logger(),
connect.static(__dirname + '/public')
);