Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple example
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
// server listens to our app
var io = require('').listen(app);
// Send current time to all connected clients
function sendTime() {
io.sockets.emit('time', { time: new Date().toJSON() });
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
socket.emit('welcome', { message: 'Welcome!' });
socket.on('i am client', function() {
console.log('received a message from the client.');
<!doctype html>
<script src=''></script>
<script src='http://localhost:3001/'></script>
var socket = io.connect('http://localhost:3001');
socket.on('welcome', function(data) {
$('#messages').append('<li>' + data.message + '</li>');
socket.emit('i am client', {data: 'foo!'});
socket.on('time', function(data) {
$('#messages').append('<li>' + data.time + '</li>');
socket.on('error', function() { console.error(arguments) });
socket.on('message', function() { console.log(arguments) });
<ul id='messages'></ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.