I hope this is not too much to ask.
Im new to this NodeJS tech, which I think is amazing, but Im not a really good programmer, I found this awesome example http://softwareas.com/video-sync-with-websocket-and-node/, but I cant make it work. I believe the code its outdated, and Im running the latest Node, I've been trying to fix it but I cant get near close.
I dont fully understand how websockets work, and is giving me a headache.
When I run the server it runs just fine.
var sys = require("util");
var ws = require('websocket-server');
var userCount = [];
var server = ws.createServer({
debug: true
});
server.addListener("connection", function(conn){
server.broadcast("userCount " + ++userCount);
conn.addListener("message", function(message){
server.broadcast(message);
});
});
server.addListener("close", function(conn){
server.broadcast("userCount " + --userCount);
});
server.listen(8000, "localhost");
function log(msg) {
sys.puts(+new Date + ' - ' + msg.toString());
};
But when I interact with the client (Log as a user) the server crashes and I get this error in the console, and I've no idea what it means.
http://i.stack.imgur.com/cLlga.png
I'm really new to this, and I don't understand D:, any help is really appreciated
That package 'websocket-server' is unmaintained for 4 years, you should consider using another one.
There have been several forks in github, https://github.com/miksago/node-websocket-server/network, but with few changes more, so they are almost same obsolete.
Trying the examples in the package, https://github.com/miksago/node-websocket-server/tree/master/test/manual, the echo-server.js (very similar to your code) doesn't work, server hangs (or appears to hang), with no traces. If you try chat-server.js it does work, but I don't know if it does what you need/want.
You can run those examples with command:
node test/manual/chat-server.js
Double check if there is a newer module that does the same :)
Related
I have made a Node.js script which checks for new entries in a MySQL database and uses socket.io to send data to the client's web browser. The script is meant to check for new entries approximately every 2 seconds. I am using Forever to keep the script running as this is hosted on a VPS.
I believe what's happening is that the for loop is looping infinitely (more on why I think that's the issue below). There are no error messages in the Forever generated log file and the script is "running" even when it's started to hang up. Specifically, the part of the script that hangs up is the script stops accepting browser requests at port 8888 and doesn't serve the client-side socket.io js files. I've done some troubleshooting and identified a few key components that may be causing this issue, but at the end of the day, I'm not sure why it's happening and can't seem to find a work around.
Here is the relevant part of the code:
http.listen(8888,function(){
console.log("Listening on 8888");
});
function checkEntry() {
pool.getConnection(function(err,connection) {
connection.query("SELECT * FROM `data_alert` WHERE processtime > " + (Math.floor(new Date() / 1000) - 172800) + " AND pushed IS NULL", function (err, rows) {
connection.release();
if (!err) {
if(Object.keys(rows).length > 0) {
var x;
for(x = 0; x < Object.keys(rows).length; x++) {
connection.query("UPDATE `data_alert` SET pushed = 1 WHERE id = " + rows[x]['id'],function() {
connection.release();
io.emit('refresh feed', 'refresh');
});
}
}
}
});
});
setTimeout(function() { checkEntry();var d = new Date();console.log(d.getTime()); },1000);
}
checkEntry();
Just a few interesting things I've discovered while trouble shooting...
This only happens when I run the script on Forever. Work's completely fine if I use shell and just leave my terminal open.
It starts to happen after 5-30 minutes of running the script, it does not immediately hang up on the first execution of the checkEntry function.
I originally tried this with setInterval instead of setTimeout, the issue has remained exactly the same.
If I remove the setInterval/setTimeout function and run the checkEntry function only once, it does not hang up.
If I take out the javascript for loop in the checkEntry function, the hang ups stop (but obviously, that for loop controls necessary functionality so I have to at least find another way of using it).
I've also tried using a for-in loop for the rows object and the performance is exactly the same.
Any ideas would be immensely helpful at this point. I started working with Node.js just recently so there may be a glaringly obvious reason that I'm missing here.
Thank you.
So I just wanted to come back to this and address what the issue was. It took me quite some time to figure out and it can only be explained by my own inexperience. There is a section to my script where my code contained the following:
app.get("/", (request, response) => {
// Some code to log things to the console here.
});
The issue was that I was not sending a response. The new code looks as follows and has resolved my hang up issues:
app.get("/", (request, response) => {
// Some code to log things to the console here.
response.send("OK");
});
The issue had nothing to do with the part of the code I presented in the initial question.
I've just picked up node.js and selenium the other day so I apologize for this introductory question but I haven't been able to find an answer on this. I've written a .js script that uses webdriverio. To use this I open 2 cmd windows (I'm running off windows 7) one where I type selenium-standalone start to get selenium to open. Then I run in the other one node ..../script.js . This gets me a beautiful browser that does what it's suppose to 1/10. The other 9/10 times I get a Session deleted due to client timeout. Since this is to be quick and easy I don't really care if it times out I just want it to restart this process. Any suggestions how to do this?
From the sounds of it, your node.js program may be trying to connect to the Selenium server, but without allowing for enough time for it to be able to establish the browser reliably too. Perhaps a case for using .pause(10000) as in:
var Selenium = function () {
this.client = webdriverio.remote(options);
};
Selenium.prototype.refreshURL = function (url, cb) {
var self = this;
this.client
.init()
.url(url)
.pause(10000)
// etc.
}
A good workaround for setting a pause is to use waitFor* - there are multiple options like
http://webdriver.io/api/utility/waitForVisible.html
or
http://webdriver.io/api/utility/waitForExist.html
.waitForVisible('body', 20000000).then(function(isVisible){
//.. you can add also small timeout here to dodge low hardware lags
});
I'm about to start coding a chat bot. However, I plan on running more than one, using a wrapper to communicate and restart them. I have done this in the past with child_process.fork(), but it was incredibly inefficient. I've looked into spawn and cluster as well, but they all seem to focus on running the same thing, not unique bots. As for plugins, I've looked into fleet, forkfriend, and workerfarm, but none seem to fit my needs.
Is there any plugin or way I'm not seeing to help me do this? Or am I just going to have o wing it again?
You can have as many chat bots as you wish in a single process. The rule of thumb in Node.js is using one process per processor core since Node has slightly different multithreading model you might got used to.
Assuming you still need some multithreading on top of this, here is a couple of node modules you might find fitting your needs:
node-webworker-threads, dnode.
UPDATE:
Now I see what you need. There is a nice example in Node.js docs, which I saw recently. I just copy & paste it here:
var normal = require('child_process').fork('child.js', ['normal']);
var special = require('child_process').fork('child.js', ['special']);
// Open up the server and send sockets to child
var server = require('net').createServer();
server.on('connection', function (socket) {
// if this is a VIP
if (socket.remoteAddress === '74.125.127.100') {
special.send('socket', socket);
return;
}
// just the usual dudes
normal.send('socket', socket);
});
server.listen(1337);
child.js looks like this:
process.on('message', function(m, socket) {
if (m === 'socket') {
socket.end('You were handled as a ' + process.argv[2] + ' person');
}
});
I believe it's pretty much what you need. Launch several processes with different configs (if number of configs is relatively low) and pass socket to a particular one from master process.
I'm learning about Meteor. Right now I'm trying to figure out how the client/server communication works, I have a file under [root]/server with all the information to connect to DB (user, password, host, port) also I have the following line of code to test this "communication"
var getUsers = function(name) {
return "Hi. I'm " + name;
};
and in my root folder I have:
console.log(getUsers("Juan!"));
however I'm getting "Uncaught ReferenceError: getUsers is not defined " error. so the question is, What I'm doing wrong????????
thanks in advance for any help or hint
Discover Meteor book have a great chapter about it:
Spanish: http://es.discovermeteor.com/chapters/publications-and-subscriptions/
English: https://www.discovermeteor.com/blog/understanding-meteor-publications-and-subscriptions/
I recommend you read the whole book, is very good.
Update:
This point of Meteor refence also explains very well the communication between methods, like server <> client communication.
http://docs.meteor.com/#meteor_call
I'm using node.js to make a http request to a host. I found the latest version of node.js of 0.6.7 that make a request is like this
var http = require('http');
var req = http.request(options, function(res) {
var result ='';
res.on('data', function (chunk) {
//console.log('BODY: ' + chunk);
result += chunk;
});
res.on('end', function () {
console.log('end:' + result);
});
});
But I also found that the 0.3 version of node.js that make a request like this
http.createClient(80, 'api.t.sina.com.cn')
.request('GET', '/statuses/public_timeline.json?source=3243248798', {'host': 'api.t.sina.com.cn'})
.addListener('response', function(response){
var result = ''
response.addListener('data',function(data){
result += data
})
.addListener('end',function(){
tweets = JSON.parse(result)
})
})
But the 0.3 version of 'createClient' api is deprecated in 0.6.7. And I don't find any docs that describe this.
I'm worrying about the api will change in the future. That will make my code not run in the future.
Can anyone give me some advice? Thanks!
The API has and will change. That's the caveat for using bleeding-edge tech, like Node. The only advice I can give is to update your code to use the latest API, after all it's not changing that often, or just stick to a working version if you don't have the resources to keep upgrading your code base.. I personally keep my Node projects pretty small, that way upgrading is easier.
Also the use of NPM modules and generally modular code is encouraged. That way some API changes are easy update. Hope this helps. :)
Node 0.3 is astonishingly ancient, and Node moves remarkably fast.
The Node API will change, you need to constantly keep your platform up to date. While this can be annoying, it's also one of the best parts of Node. It keeps people in the habit of upgrading, allowing the Node platform and ecosystem to continually improve without the stifling hassles of backwards compatibility.
If you want a less frequently changing API, perhaps PHP or Java is more suitable for you. There's also nothing stopping you from continuing to use the older versions of Node. :D