Reputation: 928
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...
Upvotes: 2
Views: 2037
Reputation: 1157
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");
});
Upvotes: 0
Reputation: 1577
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.
Upvotes: 2