Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript Globals and Socket.io
    text
    copied!<p>Is there any "globals" function in Javascript which is similar to PHP globals that would apply in this example? </p> <pre><code>var app = require('http').createServer(handler), io = require('socket.io').listen(app), fs = require('fs'), querystring = require('querystring'); app.listen(8000); var content = ''; function handler(req, res) { io.sockets.on('connection', function (socket) { if(req.method == 'POST') { var fullBody = ''; req.on('data', function(chunk) { fullBody += chunk.toString(); }); req.on('end', function() { var decodedBody = querystring.parse(fullBody); console.log(decodedBody); socket.emit('user-aaa5c8bbffe4db9', fullBody); }); } }); fs.readFile(__dirname + '/index.html', function(err, data) { if(err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } </code></pre> <p>I wrote a PHP app but I want to have notifications through socket.io but I don't want to rewrite the app for Node.js (yet) so I setup a Node server which the PHP will send a POST to and then the server will send the notification via Socket.io. I've tested the server with basic scripts and they do work. I've also tried moving the "io.sockets.on('connection', function (socket) {" inside the IF statement:</p> <pre><code>req.on('end', function() { var decodedBody = querystring.parse(fullBody); console.log(decodedBody); io.sockets.on('connection', function (socket) { socket.emit('user-aaa5c8bbffe4db9', fullBody); }); }); </code></pre> <p>But that did not produce "instant" results, the notifications would come in to the client after a page refresh.</p> <p>Client is a simple:</p> <pre><code>socket.on('user-&lt;?php echo $_SESSION['user_display_id']; ?&gt;', function (data) { alert(data); $('#events').html(data); }); </code></pre> <p>Any help would be greatly appreciated </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload