Skip to content

Instantly share code, notes, and snippets.

@chad3814
Created March 18, 2013 23:36
Show Gist options
  • Save chad3814/5192030 to your computer and use it in GitHub Desktop.
Save chad3814/5192030 to your computer and use it in GitHub Desktop.
make a directory, put this file in it, npm install socket.io, node van.js
'use strict';
var http = require('http');
var sio = require('socket.io');
var app = http.createServer(function (req, res) {
if (req.url === '/') {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.write('<input id="val">&nbsp;<button id="button">Send</button>\n');
res.write('<script src="/socket.io/socket.io.js"></script>\n');
res.write('<script>\n');
res.write(' var socket = io.connect();\n');
res.write(' socket.on("van", function (data) {\n');
res.write(' var h1 = document.createElement("h1");\n');
res.write(' var p = document.createElement("p");\n');
res.write(' h1.innerText = "Got Data";\n');
res.write(' p.innerText = data;\n');
res.write(' document.body.appendChild(h1);\n');
res.write(' document.body.appendChild(p);\n');
res.write(' });\n');
res.write(' var button = document.getElementById("button");\n');
res.write(' button.onclick = function () {\n');
res.write(' var val = document.getElementById("val");\n');
res.write(' socket.emit("some_data", val.value);\n');
res.write(' };\n');
res.write('</script>\n');
res.end();
} else {
res.writeHead(404);
res.end();
}
});
var io = sio.listen(app);
app.listen(8000);
io.sockets.on('connection', function (socket) {
socket.emit('van', 'connected!');
socket.on('some_data', function (data) {
console.log('got some_data:', data);
socket.emit('van', data); // echo it back for fun
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment