Socket.io - Cannot connect to client - javascript

I want to implement a simple socket.io connection to a client. For this purpose I use nodeJS with express.
My clients files look like that:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js" />
<!--<script src="http://fb.me/react-0.12.2.min.js"></script>-->
<script src='/javascripts/socket.js'></script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %> Juhu!</p>
</body>
</html>
socket.js
/**
* socket io connection
*/
var socket = io.connect("http://localhost:3000");
My server site looks like that:
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 app = express();
// 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);
// 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;
www.js
#!/usr/bin/env node
var debug = require('debug')('Test');
var app = require('../app');
var Pusher = require('pusher-client');
var http = require('http');
app.set('port', process.env.PORT || 3000);
//Create the HTTP server with the express app as an argument
var server = http.createServer(app);
/*var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});*/
/**
* return pusher data
*/
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function (data) {
//console.log(data);
});
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
var stream = channel.bind("message", function (data) {
//console.log(data);
});
io.sockets.on("connection", function (socket) {
// The user it's added to the array if it doesn't exist
if(users.indexOf(socket.id) === -1) {
users.push(socket.id);
}
// Log
logConnectedUsers();
/*// This is a listener to the signal "something"
stream.on("start stream", function (data) {
console.log("Test: ", data);
socket.emit('info', { data: data });
});*/
// This handles when a user is disconnected
socket.on("disconnect", function(o) {
// find the user in the array
var index = users.indexOf(socket.id);
if(index != -1) {
// Eliminates the user from the array
users.splice(index, 1);
}
logConnectedUsers();
});
});
// A log function for debugging purposes
function logConnectedUsers() {
console.log("============= CONNECTED USERS ==============");
console.log("== :: " + users.length);
console.log("============================================");
}
//server listens
server.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
I expect when opening my browser I get at least a message that a new client connected in the nodejs app. However, I get nothing.
Any recommendation what I am doing wrong?
UPDATE
I changed the following code, however I still have no connection:
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
var stream = channel.bind("message", function (data) {
//console.log(data);
});
io.on("connection", function (socket) {
// The user it's added to the array if it doesn't exist
if(users.indexOf(socket.id) === -1) {
users.push(socket.id);
}
// Log
logConnectedUsers();
socket.emit('someevent', { attr: 'value' } )
/*// This is a listener to the signal "something"
stream.on("start stream", function (data) {
console.log("Test: ", data);
socket.emit('info', { data: data });
});*/
// This handles when a user is disconnected
socket.on("disconnect", function(o) {
// find the user in the array
var index = users.indexOf(socket.id);
if(index != -1) {
// Eliminates the user from the array
users.splice(index, 1);
}
logConnectedUsers();
});
});
Thats all of my console output, when callinglocalhost:3000`
Wed, 31 Dec 2014 11:24:00 GMT Test Express server listening on port 3000
GET / 304 19.798 ms - -
GET /stylesheets/style.css 304 15.385 ms - -
UPDATE
My index.js route file:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
Update
I am now loadign my socket.js script from the client on the end of my page and get the following error message:
GET http://localhost:3000/socket.io/1/?t=1420027015782 400
(Bad Request)socket.io.min.js:2 d.handshakesocket.io.min.js:2 d.connectsocket.io.min.js:2 dsocket.io.min.js:2 c.connectsocket.js:4 (anonymous function)

What you have until now, (strictly speaking) is client connecting to server. (html+socket.js calling io.connect() ).
Maybe you're asking about sending the data from server to the client?
Inside pherris's function, you can send the data to the client with
io.on('connection', function (socket) {
console.log('a user connected')
socket.emit('someevent', { attr: 'value' } )
})
and catch it on the client side again with
var socket = io.connect("http://localhost:3000");
socket.on('someevent', function (data) { console.log(data) })
And there send another event to the server.
The communication can be done in both ways. Depends on your needs.

Related

How to setup clusters in expressjs 4.x app?

I have an expressjs generated app which is configured with socket io and I would like to implement nodejs clusters in it. The problem is that in Express 4.x the server listening configuration is in the bin/www file and no longer in app.js file.
Also my app is configured with socket io so I don't want to brake it too.
This is how it should be implemented in express apps according to this article:
app.js
// Include the cluster module
var cluster = require('cluster');
// Code to run if we're in the master process
if (cluster.isMaster) {
// Count the machine's CPUs
var cpuCount = require('os').cpus().length;
// Create a worker for each CPU
for (var i = 0; i < cpuCount; i += 1) {
cluster.fork();
}
// Listen for dying workers
cluster.on('exit', function (worker) {
// Replace the dead worker, we're not sentimental
console.log('Worker %d died :(', worker.id);
cluster.fork();
});
// Code to run if we're in a worker process
} else {
// Include Express
var express = require('express');
// Create a new Express application
var app = express();
// Add a basic route – index page
app.get('/', function (request, response) {
console.log('Request to worker %d', cluster.worker.id);
response.send('Hello from Worker ' + cluster.worker.id);
});
// Bind to a port
app.listen(3000);
console.log('Worker %d running!', cluster.worker.id);
}
And this is what I have:
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var app = express();
var io = app.io = require('socket.io')();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
var players = {};
//socket io
io.on('connection', function(socket) {
socket.on('new player', function(data) {
var player = {
id: socket.id,
name: data.name,
color: data.color
}
players[socket.id] = player;
io.to(`${socket.id}`).emit('player info', player);
});
socket.on('chat', function(data) {
io.emit('message', {
player: players[data.id],
text: data.text
});
});
socket.on('disconnect', function() {
delete players[socket.id];
});
});
module.exports = app;
bin/www
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('elvin:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '80');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = app.io
io.attach(server);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, function(){
console.log('server listening on port ' + server.address().port);
});
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
What do I do? The module.exports = app; is what it is causing me troubles
I use my own boiler plate. I used socket, cluster and express together in it. Here is a link to it.
Desktop-CHAT-app
You can download it and make the changes over here and proceed. I've used many useful packages too.
Hope it helps!

Testing API:GET localhost:3000/api/locations/_id: => loads for a longtime, returns nothing

I'm currently learning MEAN stack using this book called getting-MEAN by Simon Holmes, and I came across an issue, the book said the request mentioned in the title should return a response, that should be a full location object, stored in my MongoDB.
yet it just loads for a long time and outputs this Postman output
I'm thinking, I've messed up my enviroment versions since the book uses an older enviroment?
My environment:
✗ uname -srmo
Linux 4.11.6-3-ARCH x86_64 GNU/Linux
✗ node --version
v8.1.2
✗ express --version
4.15.0
✗ mongod --version
db version v3.4.3
git version: f07437fb5a6cca07c10bafa78365456eb1d6d5e1
OpenSSL version: OpenSSL 1.1.0f 25 May 2017
allocator: tcmalloc
modules: none
build environment:
distarch: x86_64
target_arch: x86_64
✗ npm list mongoose
loc8r#0.0.1 /home/username/github/Loc8r
└── mongoose#3.8.40
Loc8r/app_api/controllers/location.js
var mongoose = require ('mongoose');
var Loc = mongoose.model ('Location');
var sendJsonResponse = function (res, status, content){
res.status (status);
res.json (content);
};
module.exports.locationsCreate = function (req, res) {
sendJsonResponse (res, 200, {"status" : "Create success"});
};
module.exports.locationsListByDistance = function (req, res) {
sendJsonResponse (res, 200, {"status" : "ListByDist success"});
};
module.exports.locationsReadOne = function (req, res) {
Loc
.findById (req.params.locationid)
.exec (function (err, location){
sendJsonResponse (res, 200, location);
});
};
module.exports.locationsUpdateOne = function (req, res) {
sendJsonResponse (res, 200, {"status" : "success"});
};
module.exports.locationsDeleteOne = function (req, res) {
sendJsonResponse (res, 200, {"status" : "success"});
};
Loc8r/app_api/routes/index.js
var express = require ('express');
var router = express.Router ();
var ctrlLocations = require ('../controllers/locations');
var ctrlReviews = require ('../controllers/reviews');
//locations
router.get ('/locations', ctrlLocations.locationsListByDistance);
router.post ('/locations', ctrlLocations.locationsCreate);
router.get ('/locations/:locationid', ctrlLocations.locationsReadOne);
router.put ('/locations/:locationid', ctrlLocations.locationsUpdateOne);
router.delete ('/locations/:locationid', ctrlLocations.locationsDeleteOne);
//reviews
router.post ('/locations/:locationid/reviews', ctrlReviews.reviewsCreate);
router.get ('locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsReadOne);
router.put ('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsUpdateOne);
router.delete ('/locations/:locationid/reviews/:reviewid', ctrlReviews.reviewsDeleteOne);
module.exports = router;
Loc8r/app_api/models/db.js
var mongoose = require('mongoose');
var gracefulShutdown;
var dbURI = 'mongodb://localhost/Loc8r';
if (process.env.NODE_ENV === 'production') {
console.log ("NODE ENVIROMENT: "+ process.env.NODE_ENV);
dbURI = process.env.MONGODB_URI;
}
mongoose.connect(dbURI);
// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function() {
console.log('Mongoose disconnected');
});
// CAPTURE APP TERMINATION / RESTART EVENTS
// To be called when process is restarted or terminated
gracefulShutdown = function(msg, callback) {
mongoose.connection.close(function() {
console.log('Mongoose disconnected through ' + msg);
callback();
});
};
// For nodemon restarts
process.once('SIGUSR2', function() {
gracefulShutdown('nodemon restart', function() {
process.kill(process.pid, 'SIGUSR2');
});
});
// For app termination
process.on('SIGINT', function() {
gracefulShutdown('app termination', function() {
process.exit(0);
});
});
// For Heroku app termination
process.on('SIGTERM', function() {
gracefulShutdown('Heroku app termination', function() {
process.exit(0);
});
});
// BRING IN YOUR SCHEMAS & MODELS
require('./locations');
Loc8r/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');
require('./app_api/models/db');
var routes = require('./app_server/routes/index');
var routesApi = require ('./app_api/routes/index');
// var users = require('./app_server/routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'jade');
// 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')));
// tells the application to check the server application routes
// for all incoming requests
app.use('/', routes);
app.use ('/api', routesApi);
// app.use('/users', users);
// 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;
Loc8r/app_api/models/location.js
var mongoose = require('mongoose');
...
...
var locationSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
address: String,
rating: {
type: Number,
"default": 0,
min: 0,
max: 5
},
facilities: [String],
// Always store coordinates longitude, latitude order.
coords: {
type: [Number],
index: '2dsphere'
},
openingTimes: [openingTimeSchema],
reviews: [reviewSchema]
});
mongoose.model('Location', locationSchema);
Mongoshell:test query
It should return the JSON object in the Mongoshell test query, when I request GET localhost:3000/api/locations/594d96ab87e3602861443e1e
Your findById() function may be failing. Have you tried logging the err variable to see if it is throwing an error?
Loc
.findById (req.params.locationid)
.exec (function (err, location){
if(err) console.log("err", err)
sendJsonResponse (res, 200, location);
});

Express.js 'socket.io/socket.io.js 404'

I'm trying to incorporate a live user count on my website http://clickthebutton.herokuapp.com which uses Express JS. When trying to install socket.io I get this error:
GET /socket.io/socket.io.js 404 1.911 ms - 1091
Yes, I have used 'npm install socket.io --save'
I have looked around for answers, tried them and nothing has helped. If anyone thinks they know what's happening, a response would be well appreciated! Here's my code:
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 io = require('socket.io')(app);
var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var server = app.listen(app.get('port'), function () {
console.log('server listening on port ' + server.address().port);
})
var io = require('socket.io').listen(server);
// 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(path.join(__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);
// 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;
index.ejs
<!-- socket.io -->
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
</script>
</div>
</center>
</body>
routes/index.js
var express = require('express');
var router = express.Router();
var redis = require('redis'), client = redis.createClient(secret, "secret"); client.auth("secret", function() {console.log("Connected!");});
var app = express();
var server = require('http').Server(app);
var http = require('http');
var io = require('socket.io').listen(server);
io.on('connection', function(socket){
console.log('a user connected');
console.log(Object.keys(io.sockets.connected));
});
io.on('connection', function (socket) {
console.log('Socket.io connected!')
});
I only copy/pasted the code that referenced socket.io
Thanks!
In app.js alone you're creating three instances of socket.io, and once again in routes/index.js. There should be only one throughout your entire app.
A common setup for Express looks like this:
var app = require('express')();
var server = app.listen(app.get('port'), function () {
console.log('server listening on port ' + server.address().port);
});
var io = require('socket.io')(server);
If you need to reference either app, server or io in other files, you need to pass it as a variable.
EDIT: because you're using an express-generator based setup, the HTTP server will be created in bin/www and not app.js. In that case, you also need to create the socket.io server there:
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = require('socket.io')(server); // add this line
Again, if you need to reference io somewhere else in your codebase, you need to pass it along from there.

Why is socket.io giving me a 404 error?

I am basically trying to recreate a simple chat application posted on the official website of socket.io.
I created the following module in content.js:
var app = require('express');
var router = app.Router();
module.exports = function(app, io) {
app.get('/profile',function(req, res){
res.render('profile.ejs');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
return router;
};
I am calling it from index.js through this:
// socket.io
var server = require('http').Server(app);
var io = require('socket.io')(server);
require('./app/content')(app, io);
while running the app, nothing is being sent and the following error(s) are displayed in my console:
GET /socket.io/?EIO=3&transport=polling&t=1461512892706-14 404 2.370 ms - 1097
How can I fix this? as far as i read it got something to do with the location of profile.ejs? Thank you as always for any help
Here is index.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 passport = require('passport');
var flash = require('connect-flash');
var session = require('express-session');
var routes = require('./routes/index');
var morgan = require('morgan');
var users = require('./routes/users');
var home = require('./routes/home');
var mysql = require('mysql');
var helmet = require('helmet');
var app = express();
// socket.io
var server = require('http').Server(app);
var io = require('socket.io')(server);
require('./config/passport')(passport); // pass passport for configuration
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'mysql',
database: 'clearreview'
});
connection.connect();
// 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(path.join(__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')));
// security measure against xss attacks
app.use(helmet.xssFilter());
// hide powered by express
app.use(helmet.hidePoweredBy());
// security measure against sniffing
app.use(helmet.noSniff());
app.use('/', routes);
// required for passport
app.use(session({
secret: 'vidyapathaisalwaysrunning',
resave: true,
saveUninitialized: true
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
//require('./app/cr-auth-routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
require('./app/cr-auth-routes')(app, passport);
require('./app/search.js')(app, connection);
require('./app/content')(app, 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;
www file that launches the server:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('clear-review:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
It appears that you are creating two separate servers, one in your www file with:
var server = http.createServer(app);
And, another one in index.js with:
var server = require('http').Server(app);
You are never starting the one created in index.js and that's the one that socket.io is connected to so that's why you don't have any socket.io functionality. The server you bound socket.io to was never started.
You are starting the one your www file, but it has no socket.io connected to it.
You need to create one server and only one server and have that be the server that Express and socket.io are bound to. And, then you need to start that one server.

Socket.io chat application not working with express?

I need debugging help in regards to my chat application. I followed instructions from an E-Book on Socket.IO but the application will not recognize any client to server/server to client interactions. No error is reported when I run my node application so I have to idea how to debug my code. The working application should be able to send client messages to the server to be displayed by all clients with a socket connection. My "www" file in "bin" runs the node server. My folder structure is as follows:
www file:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('socketio:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
require('../routes/socket.js').initialize(server);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
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 app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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);
// 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;
public/javascripts/chat.js:
var socket = io.connect('/');
socket.on('message', function (data) {
data = JSON.parse(data);
$('#messages').append('<div class="'+data.type+'">' + data.message + '</div>');
});
$(function(){
$('#send').click(function(){
var data = {
message: $('#message').val(),
type:'userMessage'
};
socket.send(JSON.stringify(data));
$('#message').val('');
});
});
routes/socket.js
var io = require('socket.io');
exports.initialize = function(server) {
io = io.listen(server);
io.sockets.on("connection", function(socket){
socket.send(JSON.stringify(
{type:'serverMessage',
message: 'Welcome to the most interesting chat room on earth!'}));
socket.on('message', function(message){
message= JSON.parse(message);
if(message.type == "userMessage"){
socket.broadcast.send(JSON.stringify(message));
message.type = "myMessage";
socket.send(JSON.stringify(message));
}
});
});
};
layout.jade
doctype html
html
block head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(type='text/javascript', src='http://code.jquery.com/jquery-1.11.0.min.js')
body
header#banner
h1 Awesome Chat
block content
footer hope you enjoy your stay here!
index.jade:
extends layout
block append head
script(type='text/javascript', src='/socket.io/socket.io.js')
script(type='text/javascript', src='/javascripts/chat.js')
block content
section#chatroom
div#messages
input#message(type='text', placeholder='Enter your message here')
input#send(type='button', value='Send')

Categories

Resources