2

I buils small application in which I use socket.io and expressjs

Server side

var express = require('express'),
sio = require('socket.io');
var app = express.createServer();

app.configure('development', function(){
app.use(express.bodyParser());
app.use(express.cookieParser());
    app.use(express.static(__dirname + '/'));
    app.set('views', __dirname + '/views');
    app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
    app.use(app.router); 
});
app.listen(4000);
var io = sio.listen(app);

app.get('/', function (req, res) {
     res.redirect('index.html');
});

io.sockets.on('connection', function (socket) {

       app.post('/mysegment',function(req,res){
            var userData = req.body;
            socket.emit('sendUser', userData);
            res.send("yes I got that segment");
       });
       socket.on('getUser',function(msg){
            console.log("Yes Socket work Properly "+msg);
       });
});

And index.html

var socket = io.connect();
socket.on('connect', function () {
    console.log("client connection done.....");
});
socket.on('sendUser', function (data) {
     alert("On send user");
     socket.emit('getUser',"Hello");
});

This demo work perfectly But When I refresh page And send post request to "/mysegment" that I time socket does not work properly. I do not get message on my console "Yes socket work properly(and my msg)" But I got response "Yes I got that segment" Any suggestion please...

Paresh Thummar
  • 933
  • 7
  • 20
  • You confusing a post request with sockets. How are you sending the post request anyways? – Amit Apr 12 '12 at 07:25
  • At first time it runs Perfectly but whenever I refresh the page that time client socket refreshed but not server side so that socket in server side does not emit request(I think it does not recognize newly generated socket). In short, I want such application which emit socket whenever someone post data on /mysegment url – Paresh Thummar Apr 12 '12 at 10:15

2 Answers2

2
io.sockets.on('connection', function (socket) {

   app.post('/mysegment', ...

What is happening here, is that each time any client connects with websockets, a new handler is added to all /mysgment POST request. Then, when anybody send a POST to /mysegment, all connected clients will get userData... which is probably not what you want.

To keep it simple, stick to using sockets for one thing, and normal HTTP for others.

Otherwise you'll have to share the session and/or find the corresponding socket.

Community
  • 1
  • 1
Gipsy King
  • 1,549
  • 9
  • 15
0

You can access the socket object in your express routes like this (in scoket.io v4):

var socket = io.sockets.on('connection', function (socket) {
  socket.on('getUser',function(msg){
    console.log("Yes Socket work Properly "+msg);
  });
});

app.post('/mysegment',function(req,res){
  var userData = req.body;
  socket.emit('sendUser', userData);
  res.send("yes I got that segment");
});
froston
  • 1,027
  • 1
  • 12
  • 24