This is probably a simple mistake. I have a nodejs server running socket.io, I have got everything to work within the server.
However, I want to be able to make a CURL post via PHP to the node server, and have it emit the data. I can make the server receive the request, but when I try to emit the data, I get an error saying that the socket is not defined.
This is obvious in my code. My question is, how do I require socket.io before I setup the server? Hopefully a segment my code will help explain my problem:
var http = require('http')
, url = require('url')
, fs = require('fs')
, server;
server = http.createServer(function(req, res) {
// your normal server code
var path = url.parse(req.url).pathname;
switch (path){
case '/':
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<h1>Hello! <a href="/index.html">Enter</a></h1>');
res.end();
break;
case '/index.html':
fs.readFile(__dirname + path, function(err, data){
if (err) return send404(res);
res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
res.write(data, 'utf8');
res.end();
});
break;
case '/write.html':
fs.readFile(__dirname + path, function(err, data){
if (err) return send404(res);
res.write(data, 'utf8');
res.end();
});
break;
case '/post':
console.log(req.toString());
socket.broadcast.emit('user', {state: 'PHP Post', userid: 'PHP'});
res.writeHead(200);
res.end();
break;
default: send404(res);
}
}),
send404 = function(res){
res.writeHead(404);
res.write('404');
res.end();
};
server.listen(843);
// socket.io
var io = require('socket.io').listen(server);
// Regular socket.io events
That part is pretty easy; at the top of your file, do something like:
and at the bottom:
The problem is, in your
POSThandler, you’re usingsocket.broadcast.emit, butsocketisn’t defined. Are you trying to send a message to all Socket.IO users? If so, you can useio.sockets.emit; I’d probably do something like this:If you’re trying to send data to a single socket, or every socket except for a particular one (which is how you’d normally use
socket.broadcast), you’ll somehow need to map HTTP requests to Socket.IO sockets; using sessions for this is common.