Sunday, June 15, 2014

Node.js + socket.io, receive data from client

Example to get data from client using Node.js + socket.io.


To use socket.io, you have to install it using npm
$ npm install socket.io

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);
    });
});

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>

<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 });
}
</script>

</body>
</html>

No comments:

Post a Comment