Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Socket.io and Express 3

Socket.io and Express 3

Problem

I created a Express 3 app with the express generator and installed socket.io. On app.js im emiting a message:

io.sockets.on('connection', function(socket) {
  socket.emit('init', { msg: 'Welcome'});
});

At Server side I wrote:



  
    

Welcome to

If I run app.js It should print "Welcome" on the console, but its not priting anything. I checked if /socket.io/socket.io.js is accesed and it does.

When running the app I get:

  info  - socket.io started
Express server listening on port 3000
GET / 200 28ms - 472
GET /stylesheets/style.css 200 163ms - 110
   debug - served static content /socket.io.js

Am I missing something? I followed the socket.io webpage examples, but it seems that server is running fine... maybe something at the client-side?

EDIT: I also tried var socket = io.connect('http://127.0.0.1', { port: 3000 } ); on the client side, and also running all socket client side from the body.

Doing a console.log on the io.sockets.on event gave nothing... so "connection" is never reached.

Problem courtesy of: jviotti

Solution

adding a index.jade file to the example I posted before

server.js

var app = require('express')()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server)

server.listen(3000)
io.set('loglevel',10) // set log level to get all debug messages
io.on('connection',function(socket){
  socket.emit('init',{msg:"test"})
})
app.get('/',function(req,res){
  res.render('index.jade')
})

/views/index.jade

doctype html
html
  head
    script(src="/socket.io/socket.io.js")
    script.
      var sockets = io.connect()
      sockets.on('init',function(msg){
        alert(msg.msg)
      })
Solution courtesy of: supernova

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Socket.io and Express 3

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×