So I’ve spent the day taking tutorials on socket.io and I’ve found myself completely stuck due to the overwhelmingly low amount of tutorials out there. I would like to use socket.io in order to send a variables to a PHP page and retrieve/display information.
Super simple app.js (socket.io server)
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function (socket) {
socket.on('message', function () { });
socket.on('disconnect', function () { });
});
Super simple socket.io index page.
<script>
var socket = io.connect('http://localhost/');
socket.on('connect', function () {
socket.send('hi');
socket.on('message', function (msg) {
// my msg
});
});
</script>
the php file I want to send the information to…
<?php
$hostname = 'localhost';
$username = 'root';
$password = 'root';
$database = 'database';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT * FROM comments WHERE pid = :pid");
$pid = $_GET['pid'];
$stmt->bindParam(':pid', $pid, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$stmt->execute();
echo $stmt->rowCount();
$dbh = null;
?>
So essentially all I want to do is use the websocket to send the id of my posts to the PHP page and retrieve the count, automatically updating the count as people vote. Yet I can’t find (or figure out) how to accomplish this.
Anyone here familiar with node.js/socket.io that can lend me a hand here?
Node.js and your PHP server are two independent servers. What you can do is get the HTML document from PHP server and send it back to the client using socket.io . Or may be redirect the page depending on the inputs from web socket.
If you want to send some data to client (HTML page, not the PHP) then that is the purpose of socket.io.
you can do this like this,
When people vote, send data to node server (+1) count,
then Broadcast the updated vote count using socket.io (may be you can call PHP and save the vote count too),
Here is how to call a web page (your PHP server) withing your node server..
you can get more ideas from here