express js - socket io connection - node.js

Unable to integrate socket io and express js .
Below is my html code.
<html>
<head>
</head>
<body>
hello world.
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
</script>
</body>
</html>
This is my app.js of express 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();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// 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(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.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
io.on('connection', function(socket){
console.log('client connected.');
});
// 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;
Problem : Unable to connect socket io with express.
Below is the image which shows errors in developer console, when i run the app.

Using your same code, removing var routes = ... and var users = ...
and adding at the end server.listen(3000); instead of the exports it just works for me.
https://dripr.io/file/NkWBbbHR

This code works for me
const express = require('express')
const socketIo = require('socket.io')
const http = require('http')
const app = express()
const server = http.createServer(app)
const io = socketIo(server)
io.on('connection',(socket)=>{
console.log('client connected: ',socket.id)
socket.on('disconnect',(reason)=>{
console.log(reason)
})
})
server.listen(5000, err=> {
if(err) console.log(err)
console.log('Server running on Port ', PORT)
})

const http = require("http");
const port = 4000;
const { joinUser, removeUser, findUser } = require('./users');
const app = http.createServer((req, res) => {
res.writeHead(200, headers);
res.end("API");
return;
});
const server = app.listen(port, () => {
console.log('Server Started..');
});
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
io.on('connection', (socket) => {
console.log('socket connected..', socket.id);
socket.on('chat', (data) => {
io.sockets.emit('send data', {
id: socket.id
});
io.sockets.emit('chat', { data: data, id: socket.id });
});
socket.on('typing', (data) => {
socket.broadcast.emit('typing', data);
});
socket.on("disconnect", () => {
const user = removeUser(socket.id);
console.log(user);
if (user) {
console.log(user.username + ' has left');
}
console.log("disconnected");
});
});

Related

How to link app.js to html page,so that I should display the progress bar in the browser using socket.io

I'm unable to link the index.html page to app.js.I'm trying to send the progress to index.html.But,I'm failing here.How can I overcome this issue?Can anyone please help me out ...
My index.html :
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.css" />
<div id="progressbar">
</div>
<script>
var socket = io('http://localhost:8085');
socket.on('connect', function(){});
socket.on('message', function(data){
$('#progressbar').progressbar({
maximum: 100,
step: JSON.parse(data).percent
});
});
socket.on('disconnect', function(){});
</script>
My app.js :
var fs = require('fs');
var request = require('request');
var progress = require('request-progress');
var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'googlenew.png'
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log("connected :"+socket.id);
});
var callback = function(state){
console.log('received size in bytes', state.received);
console.log('total size in bytes', state.total);
console.log('percent', state.percent);
io.sockets.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));
}
progress(request('https://www.google.com/images/srpr/logo3w.png'), {
throttle:0,
delay: 0
})
.on('progress', callback)
.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
console.log("error");
})
.on('close', function (err){
console.log("Download Complete");
})
Updated 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 fs = require('fs');
var request = require('request');
var progress = require('request-progress');
var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'googlenew.png'
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var server = app.listen(8085, function(){
console.log('listening on *:8085');
});
var io = require('socket.io')(server);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log("connected :"+socket.id);
});
var callback = function(state){
console.log('received size in bytes', state.received);
console.log('total size in bytes', state.total);
console.log('percent', state.percent);
io.sockets.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));
}
progress(request('https://www.google.com/images/srpr/logo3w.png'), {
throttle:0,
delay: 0
})
.on('progress', callback)
.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
console.log("error");
})
.on('close', function (err){
console.log("Download Complete");
})
// 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;
You are not initializing Express properly so app is not hooked to any web server and thus app.get() isn't active.
Change this:
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
to this:
var app = express();
var server = app.listen(8085, function(){
console.log('listening on *:8085');
});
var io = require('socket.io')(server);
See the basic "Hello World" app example in the ExpressJS doc.
And, you will also need to make routes for jquery.js, bootstrap.js, etc... Remember, node.js doesn't serve any files by default. Since they are static files, you will probably want to use app.use(express.static(...)) to serve the static files.

simple express and socket example does not work

i use express 4 with socket.io.
when server is running, socket does not work.
console does not print 'user connect'.
client button does not work.
please help me. :-(
this is 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 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.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
// 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;
io.js
var io = require('socket.io')();
io.on('connection', function(socket) {
console.log('user connected');
socket.on('rint', function(data) {
console.log('user send data : ' + data);
socket.emit('smart', data);
});
});
module.exports = io;
/bin/www
\#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var io = require('../io');
var debug = require('debug')('socketT: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);
io.attach(server);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
...
index.html
<!DOCTYPE html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
window.onload = function() {
var socket = io();
socket.on('smart', function(data) {
alert(data);
});
document.getElementById('button').onclick = function() {
var text = document.getElementById('text').value;
socket.emit('rint', text);
});
});
</script>
</head>
<body>
<input type="text" id="text" />
<input type="button" id="button" value="echo" />
</body>
</html>
Your listener for everything on the server-side is on("connection", ... but you don't make that connection anywhere on the client side.
Check out the following page: http://socket.io/docs/
You will need to add the url of the server you are connecting:
index.html:
var socket = io("localhost:8080"); //Or whatever your url and port are.

Why can not my client get socket.io.js?

I am learning to use socket.io, but when I add
script(type='text/javascript', src='/socket.io/socket.io.js')
in my client, and I add code:
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('------------connection');
});
in app.js, but my client do get 404 error when trying to get /socket.io/socket.io.js.
I chage my code to :
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();
var server = require('http').createServer();
var io = require('socket.io').listen(server);
// 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);
var userlist = {};
io.on('connection', function(data){
console.log('------------connection');
socket.name = data.user;
if (!userlist[data.user]) {
userlist[data.user] = data.user;
};
io.emit("online", { userlist: userlist, user: data.user});
});
// 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: {}
});
});
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
module.exports = app;
and I also have the code as follow in my javascript:
$(document).ready(function() {
var socket = io.connect('http://localhost:3000');
// other code
}

How do you export a variable from app.js into another route in Node js

i'm using socket.io in my node project and wanted to know how to possibly export the io variable
this is what i have done so far but i get this error: Object #<Object> has no method 'on'
in 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')(io);
var users = require('./routes/user');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);
require('./routes/index')(io);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
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,
title: 'error'
});
});
}
// 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: {},
title: 'error'
});
});
/*
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
*/
module.exports = app;
in index.js
var io = require('../app');
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
the reason i want export the variable is so that i dont have to define io is index.js like i did in app.js which leads to me basically defining both server and app variable !
I just want to do all my socket.io stuff in the index.js route essentially (except from having to redefine the app, server and io variables in index.js ) !
Hope i have explained my self enough
Thank you !
Your dependencies are not set up correctly. You are executing index.js before io is initialized
var routes = require('./routes/index');
/* index.js starts being executed at this point
* hence, io is undefined inside index.js
*/
Instead, why don't you try
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);
module.exports = io;
var routes = require('./routes/index');
var users = require('./routes/user');
index.js
var io = require('../app');
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I think you need to use the sockets.
io.sockets.on('connection', ... );
It looks like a circular dependency (app.js requires index.js and index.js requires app.js)
Try this.
change app.js to:
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 users = require('./routes/user');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(4000);
require('./routes/index')(io);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
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,
title: 'error'
});
});
}
// 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: {},
title: 'error'
});
});
/*
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
*/
module.exports = app;
change index.js to:
module.exports = function(io){
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
}
Use "global.io" instead of "var io" in app.js

Socket.io Chat Application Refreshes When I Send a Message

I am trying to make a simple chat application using Node.js, socket.io, and express. However, if I click the send button in the main.jade file, the page refreshes, and no message appears. I also get this error in Firebug:
The connection to ws://127.0.0.1:3000/socket.io/?EIO=2&transport=websocket&sid=d_hNMPdXHed-j7LrAAAH was interrupted while the page was loading.
Main.jade
doctype html
html
head
meta(charset = "UTF-8")
script(src="/socket.io/socket.io.js")
script(src="http://code.jquery.com/jquery-1.11.1.js")
script.
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
body
ul#messages
form(action = "")
input#m(type = "text")
button Send
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 mongo = require('mongodb');
var mongodb = require("mongodb");
var monk = require('monk');
var db = monk('localhost:27017/pesterchum');
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(function(req,res,next){
req.db = db;
next();
});
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
#!/usr/bin/env node
var debug = require('debug')('app');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket){
socket.on('chat message', function(msg){
io.sockets.emit('chat message', msg);
});
});
index.js
var express = require('express');
var router = express.Router();
/* GET Main page. */
router.get('/main', function(req, res) {
res.render('main', { title: 'Main'});
});
It seems that the page is being reloaded because you've forgotten to wrap your client js code with $(document).ready(function() { ... });

Resources