Tuesday, June 17, 2014

Node.js + socket.io, emit events between server and client, bi-directionally.



server.js
var serverapp = require('http').createServer(handler);
var io = require('socket.io').listen(serverapp);
var fs = require('fs');

serverapp.listen(8888);

function handler (req, res) {
    fs.readFile("page.html",
        function (err, data) {
            if (err) {
                throw err; 
            }
            res.writeHead(200);
            res.end(data);
        });
}

io.sockets.on("connection", function (socket) {
    socket.on("event_button_clicked", function (data) {
        console.log(data.text);
        io.sockets.emit("event_upatetext", { value: "hello " + data.text});
    });
});

page.html
<html>
<head></head>
<body>
<h1>Hello World!</h1>
<p>from mobile-web-app.blogspot.com</p>

<form action="">
<input 
    type="text" id="intext"><br>
<input 
    type="button" 
    id="button1" 
    value="Click ME" 
    onclick="button_clicked(this);">
</form>
<p id="outtext"></p>

<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);

function button_clicked(button)
{
    socket.emit(
        "event_button_clicked", 
        { text: document.getElementById("intext").value });
}

socket.on("event_upatetext", function (data) {
    console.log("event_upatetext" + ": " + data.value);
    document.getElementById("outtext").innerHTML = data.value;
});
</script>

</body>
</html>


No comments:

Post a Comment