简体   繁体   中英

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM