Created
March 18, 2013 23:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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"> <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