node.js - Socket IO cant connect to server when running express -
node.js - Socket IO cant connect to server when running express -
i trying write little app using node.js express.js , scoket.io.
the server runs fine , can serve html , other static content. im having hell of time getting clients connect via socket.io server.
when don't utilize express express works fine, express can't seem cooperate. not sure if there special considerations when using express , socket.io in conjunction.
part of me things route issue?
it looks when socket tries connect 404'ing
get http://localhost:3000/socket.io/1/?t=1403186531515 400 bad request 1ms
server code:
var express = require('express') , app = express() , http = require('http') , server = http.createserver(app).listen(3000) , io = require('socket.io').listen(server) , favicon = require('static-favicon') , logger = require('morgan') , cookieparser = require('cookie-parser') , session = require('express-session') , routes = require('./routes/index') , path = require('path') , bodyparser = require('body-parser'); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hjs'); app.use(favicon()); app.use(logger('dev')); app.use(bodyparser.json()); app.use(bodyparser.urlencoded()); app.use(cookieparser()); app.use(session({secret: 'keyboard cat'})); app.use(require('less-middleware')(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', routes); // grab 404 , forwards error handler app.use(function(req, res, next) { var err = new error('not found'); err.status = 404; next(err); }); // error handlers // development error handler // 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 user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); io.sockets.on('connection', function (socket) { //message new connection socket.emit('message', { message: 'message server.' }); //message connections socket.on('send', function (data) { io.sockets.emit('message', data); }); });
client code:
** html , other js omitted ** <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script> <script> var socket = io.connect('http://localhost:3000'); </script>
i have tried
var socket = io.connect('ws://localhost:3000');
to no avail.
thanks help!
try swapping order of when bind server port:
var express = require('express') , app = express() , http = require('http') , server = http.server(app) , io = require('socket.io').listen(server) server.listen(3000);
shoutout doug wilson his comment on github helped me solve issue.
node.js express socket.io http-status-code-404
Comments
Post a Comment