Reputation: 43
I don't understand why my connection waits for local host and then eventually times out. I've read and reread my code a million times and now I'm stumped. Please help. It says it is listening on the port..
Also, I have redacted some of the code, but as you can see I will need my sockets, express and http running on the same port. Thank you in advance!
var express = require("express");
var server = require ("http").createServer(app)
var io = require("socket.io")(server);
var mongo = require("mongodb").MongoClient;
var bodyParser = require("body-parser");
var methodOverride = require('method-override');
var logger = require('morgan');
var serveStatic = require('serve-static');
var errorhandler = require('errorhandler');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(serveStatic(path.join(__dirname, 'public')));
if (process.env.NODE_ENV === 'development') {
app.use(errorHandler());
}
app.get("/", function(req, res) {
res.send("index")
});
io.on("connection", function(socket) {
console.log("a user connected..");
mongo.connect(MONGOLAB_URI, function(err, db) {
if(err) {
console.log("error connecting to mongo db")
} else {
var collection = db.collection("chat messages")
var stream = collection.find().sort().limit(10).stream();
stream.on("data", function(chat) {
console.log("emitting chat");
socket.emit("chat", chat.content);
});
}
});
socket.on("disconnect", function() {
console.log("user disconnected");
});
socket.on("chat", function (msg) {
mongo.connect(MONGOLAB_URI, function(err, db) {
if(err) {
console.log("error");
} else {
var collection = db.collection("chat messages");
collection.insert({content: msg}, function(err, doc) {
if (err) {
console.log("error insterting msg to database")
} else {
console.log("inserted " + msg + "to db - content")
}
});
}
});
socket.broadcast.emit("chat", msg);
});
});
server.listen(app.get("port"), function (err, data) {
if (err) {
console.log(err)
};
console.log("listening on " + app.get("port"));
});
Upvotes: 3
Views: 764
Reputation: 1216
something seems a bit off on your listen(), I don't see the API in server.listen() that takes a callback with the parameters of err and data. By the looks of it there are no parameters in the callback. just make it an empty anon function, are you sure you are not getting any other errors?
--edit found an issue with your mongodb collection, you are using sync not a-sync for the collection method, there is a chance that collection is undefined. do this instead
socket.on("chat", function(msg) {
mongo.connect(MONGOLAB_URI, function(err, db) {
if (err) {
console.log("error");
}
//don't do spaces in collection names - make it async with callback
db.collection("chatmessages", function(err, col) {
if (err) {
console.log(err)
return;
}
col.insert({ content: msg}, function(err, doc) {
if (err) {
console.log("error insterting msg to database")
return;
}
console.log("inserted " + msg + "to db - content")
});
});
});
});
--EDIT Below
var http = require('http');
var express = require('express');
var mongodb = require('mongodb');
//other stuff
var app = express();
//do all your app.use() here
//add all your routes here.
//so if routes where in a different file theortically
//you would have requires them in at the top like var routes = require('./routes');
//and here you would do app.use(routes);
var server = http.createServer(app);
//now you can require your io here
var io = require('socket.io')(server) //because server is now filled with all the configuration
//do you io events down below..
essentially when you do var app = require('express')(); it will do the same thing as var express = require('express'); var app = express(); you're just chaining the calls together not depreciated or new.
Upvotes: 0
Reputation: 43
WOW!! I figured it out! There was nothing essentially wrong with my code (although async Mongo is definitely the better practice) except the way I was requiring express. My code was var express = require("express"); and then I would set an app variable like so: var app = express(). That method is outdated and no longer works. The correct way to use express and set an app variable is: "var app = require("express")();" That subtle change allowed my server to work properly. Thank you so much for assisting me and pointing out to me the better, asynchronous use of mongo. I'm so happy! haha EDIT: It appears, the issue is not an outdated method, rather it is the order in which I defined my app variable. "app" was being required prior to it being defined.
Upvotes: 1