Skip to content

Instantly share code, notes, and snippets.

@slickplaid
Created May 27, 2011 23:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save slickplaid/996384 to your computer and use it in GitHub Desktop.
Save slickplaid/996384 to your computer and use it in GitHub Desktop.
Simple example
<!-- put me in public/index.html -->
<!doctype html>
<html>
<head><title>Testing Express, Socket.io in Node.js</title></head>
<body>
<h1>Test!</h1>
<div class="m"></div>
<button>Send Message</button>
<!-- CHANGE to server hostname:port/socket.io/socket.io.js -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script src="//hercules:3020/socket.io/socket.io.js"></script>
<script>
var socket = new io.Socket();
socket.connect();
socket.on('connect', function(){ $('.m').append('Connected at '+new Date()+'<br>'); })
socket.on('message', function(message){
if(message.alert){ $('.m').append('New Message: '+new Date()+': '+message.alert+'<br>'); }
console.log(message);
})
socket.on('disconnect', function(){ $('.m').append('Disconnected at '+new Date()+'<br>'); })
$(function(){
$('button').click(function(){
$('.m').append('Sending Message: '+new Date()+': "Sent at '+new Date()+'"<br>');
socket.send({ alert: 'Sent at '+new Date() });
});
});
</script>
</body>
</html>
connect = require 'connect'
express = require 'express'
io = require 'socket.io'
app = express.createServer();
app.configure ->
app.set 'views', __dirname + '/views'
app.use connect.bodyParser()
app.use connect.static __dirname + '/public'
app.use app.router
app.listen 3020
io = io.listen app
io.on 'connection', (client)->
client.broadcast JSON.stringify { alert: "User connected! Server time is now #{ new Date() }" }
client.on 'message', (message) ->
client.broadcast message
client.send message
@stygeo
Copy link

stygeo commented May 28, 2011

That still doesn't work you know. App isn't defined before require express.

@slickplaid
Copy link
Author

Should work now :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment