Socket.io Connection Event Not Firing - javascript

I know that the socket is connected but the event isn't firing.
Server:
var express = require('express'),
path = require('path');
var app = express(),
server = require('http').createServer(app);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
/* Socket.io stuff */
var io = require('socket.io')(server);
io.use(function(socket, next) {
auth.session(socket.request, socket.request.res, next);
});
//On socket connection
io.sockets.on("connection", function(socket) {
console.log("Socket connected");
});
/* Start server */
server.listen(3000, function () {
console.log("Listening on port 3000");
});
/* Mount routers */
var auth = require('./routes/auth'),
index = require('./routes/index');
app.use('/', index.router);
app.use('/auth', auth.router);
/* Exports */
module.exports = app;
Pug file:
html
head
link(rel='stylesheet', href='/stylesheets/chat.css')
script(src="http://127.0.0.1:3000/socket.io/socket.io.js")
script(type='text/javascript', src='../javascripts/chat.js')
body
include nav.pug
.chat
.chat-messages
.chat-message
| Alex: Hello There
.chat-message
| Billy: Hello There
input.chat(type="text", placeholder="enter ur message")
Clientside Javascript:
try {
var socket = io.connect('http://127.0.0.1:3000');
} catch(e) {
//Set status to warn user
console.log(e);
}
I know that the socket is connecting because it there are no returned errors. Also I can manually call var socket = io.connect("http://127.0.0.1:3000");
in the console and it returns undefined but the connection event still does not fire. Any idea on how I can fix this?

Related

socket.io not working with node server

I'm trying to set up my node server to update all the connected clients with new information in real-time. When I run the code below, the io.sockets.on('connection') callback is fired constantly, flooding the console with the message Client connected!, and the front-end is not being updated from socket.emit(). What am I doing wrong?
app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var models = require('./models.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
// Connect to the Mongo database
mongoose.connect('mongodb://localhost/test');
bin/www.js
#!/usr/bin/nodejs
var debug = require('debug')('my-application');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var io = require('socket.io').listen(app.listen(app.get('port')));
io.sockets.on('connection', function(socket) {
console.log('Client connected!');
socket.on('message', function(data) {
console.log('Sending update!');
socket.emit('update', 'Working!');
});
});
public/javascripts/update.js
var socket = io.connect('http://' + document.location.hostname + ':3000/');
socket.on('connect', function() {
console.log('Socket connected!');
socket.emit('message', 'Message from client');
});
socket.on('update', function(data) {
alert(data);
});
And when I end the npm process, the client begins to log
http://<ip>:3000/socket.io/?EIO=2&transport=polling&t=1498772846992-691 net::ERR_CONNECTION_REFUSED
I've read posts about the express router messing with the socket requests but I can't seem to get it working no matter what I try.
Can you try this setup?
EDITED:
app.js:
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.get('/', function (req, res) {
res.render('index');
});
module.exports = app;
bin/www.js:
var app = require('../app');
var http = require('http');
var server = http.createServer(app);
server.listen(process.env.PORT || '3000', function () {
console.log('server listens on port 3000');
});
var io = require('socket.io')(http);
io.listen(server);
io.on('connection', function(socket) {
console.log('Client connected!');
socket.on('message', function (data) {
console.log('Sending update!');
socket.emit('update', 'Working!');
});
});
index.pug (or jade, they say jade is obsolete):
doctype html
html
body
h1 Testing socket.io
h3#status not connected
br
p#update update:&nbsp
script(src="/socket.io/socket.io.js")
script.
var socket = io();
socket.on('connect', function() {
document.getElementById("status").innerHTML = "connected";
socket.emit('message', 'Hello!');
});
socket.on('update', function (data) {
document.getElementById("update").innerHTML += data;
});
Calling app.listen (where app is the result of invoking express()) returns an HTTPServer, which can be used to setup the socket connection:
var server = app.listen(port);
var io = socket(server);
without manually running your solution, I'd guess that because you're creating a new HTTPServer to be feed into the socket, it's somehow getting hung in a loop.

Duplicates when I use socket.io in express.js route files

I have a problem with Node.JS/Socket.IO/Express.JS and i didn't find any solution.
I use:
"express": "~4.10.6"
"socket.io": "1.2.1"
on Ubuntu Linux
My problem is that when I run the server and access localhost:3000/chat at the first run all works great but after a refresh/2/3/4 the messages inserted in chat duplicates. For one refresh, i have to identical message on one submit. For two refreshes, I have 3 identical message and so on. This behaviour began when i put the socket functionality in express.js routes folder.
P.S. I'm new to node.js/socket.io/express.js
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var chat = require('./routes/chat');
var app = express();
// Socket IO Things
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
// END - Socket IO Things
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/chat', chat.random_function(io));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
server.listen('3000');
/routes/chat.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
module.exports = {
router: router,
random_function: function(io) {
return function(req, res){
res.sendFile(__dirname + '/index.html');
io.sockets.on('connection', function (socket) {
socket.on('send message', function (data) {
io.sockets.emit('new message', data);
});
});
}
}
};
Client side sockets (routes/index.html)
<html>
<head>
<title>Chat with socket.io and node.js</title>
<style>
#chat {
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="chat-message" action="">
<input size="35" id="message"></input>
<input type="submit"></input>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
var $messageForm = $('#chat-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val("");
});
socket.on('new message', function(data){
$chat.append(data + "<br>");
});
</script>
</body>
</html>
How can I handle this problem? Thanks in advance! I also checked the debugger and on server come 1/2/3/4/5 different packages each time.
You're creating & attaching new connection listener on each /chat request. Try moving it outside of random_function and perhaps creating separate socket instance for each connection/client.
(Edit) code added:
Try this (should work, but I didn't test it)
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var chat = require('./routes/chat');
var app = express();
// Socket IO Things
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.on('send message', function (data) {
io.sockets.emit('new message', data);
});
});
// END - Socket IO Things
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/chat', chat.random_function);
routes/chat.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
module.exports = {
router: router,
random_function: function(req, res){
res.sendFile(__dirname + '/index.html');
}
};

node.js TypeError: Object has no method get

I'm trying to separate server initiation and other calls from the core file(app.js) but when I try to run it, it issues me error that
http.createServer(app).listen(app.get('port'), function(){
^
TypeError: Object function (){ all code from app.js file }
has no method 'get'
This is app.js file.
/**
* Module dependencies.
*/
module.exports = function(){
var express = require('express');
var routes = require('./routes');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 4000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
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('/', routes.index);
return app;
};
and this is server.js file.
var http = require('http'),
app = require('./app');
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
using express#3.4.0
what am I missing OR doing wrong.. please help.
You have no reason to return a function into your app.js file, just return the express object:
var express = require('express');
var app = express();
// ... more variables
// ... the rest of your code
module.exports = app;
Then, the rest of your code into server.js will work fine.
Remember that module.exports works like a "return" into CommonJS (and therefore NodeJS).
See documentation.
You're passing a function to module.exports, so when you require('./app'), you need to call it like a function:
var http = require('http'),
app = require('./app')();
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});

Using Socket.io with Node.js, Express and Jade

I have some trouble to use Socket.io even just to test if a client is connected. I've tried many things and I think that my mistake is, maybe, when I do the app.get function. I have also tried to do this in an route js file but it wasn't conclusive neither. So here are my different codes :
App.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('mongodb://xxxxx:xxxxx#ds051067.mongolab.com:51067/jdo');
var app = express(),
server = http.createServer(app) ,
io = require('socket.io').listen(server);
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('This is secret'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
io.sockets.on('connection', function (socket) {
console.log('Un client est connecté !');
});
// app.get('/', routes.index);
app.get('/users', user.list);
app.get('/deplacement',routes.deplacement);
app.get('/monCompte', routes.compte);
app.get('/connexion', routes.connexion);
app.get('/', function(req, res) {
res.render('index.jade');
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Index.jade
extends layout
block content
script(src="/socket.io/socket.io.js").
var socket = io.connect('http://localhost:3000');
});
PS : Sorry if my english is bad ^^
You can't use inline javascript in the same script tag as an included script.
extends layout
block content
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect('http://localhost:3000');

Node Express 3x socket IO testing

I try to add socket IO to my project but I didn't manage to make it work.
my app.js
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
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('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
//IO Config
var io = require("socket.io").listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('makealert');
});
my views:
extends layout
script(type='text/javascript' src='../node_modules/socket.io/lib/socket.io.js')
script(type='text/javascript'
var socket = io.connect();
socket.on('makealert', function () {
alert('Boom');
});
)
block content
h1= title
p Welcome to #{title}
my route:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
I have 2 problems:
-first what's the way to find socket.io.js (in a jade view)
-second, is my app.js OK ?
-thrid, my console said:
SyntaxError:
Node/thrid_app/demo-express/views/index.jade:5
3| script(type='text/javascript' src='../node_modules/socket.io/lib/socket.io.js')
4|
5| script(type='text/javascript'
6| var socket = io.connect();
7| socket.on('makealert', function () {
Ty for yours helps
The error you have mentioned is due to syntax error in jade
change this line
script(type='text/javascript'
var socket = io.connect();
socket.on('makealert', function () {
alert('Boom');
});
)
to
script(type='text/javascript')
var socket = io.connect();
socket.on('makealert', function () {
alert('Boom');
});
Some mistakes in your code, also you seem to be using old jade syntax.
You are missing a comma in script(type='text/javascript' src='../'). It should be script(type='text/javascript', src='../')
Since jade 0.31, script must be used as script. or script(...).. Likewise for style.
Your last script tag in view is closed incorrectly
script(type='text/javascript'
...
)
Should be like this
script(type='text/javascript')
...

Categories