HTML and CSS Reference
In-Depth Information
To become familiar with Socket.io before building a game using the library, you'll build a simple multiuser
scribble application that enables people to scribble over each other's drawings in real time.
Creating the Scribble Server
On the server side, Socket.io works by listening for connection events. These events trigger a callback with
a socket object. You can then attach additional listeners for both standard events, such as disconnect and
custom named events.
To send data you can call socket.emit with a name for the event and any data that needs to be passed
along. You can send events to all sockets except the socket itself by calling socket.broadcast.emit .
To create the scribbler, first create a package.json file for the dependencies. Create a new project directory
called scribble , and add the package.json file in Listing 21-2 to it.
Listing 21-2: Scribbler package.json
{
"name": "scribbler"
, "version": "0.0.1"
, "private": true
, "dependencies": {
"express": "2.5.8",
"socket.io": "0.9.6"
}
}
Now run npm install from the command line in that directory to grab the dependencies—Socket.io has
a few.
Next, create your app.js file, and add the code from Listing 21-3 to it.
Listing 21-3: The Scribbler app.js
var express = require('express'),
app = express.createServer(),
io = require('socket.io').listen(app);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
app.listen(3000);
// Clear the board every 60 seconds
setInterval(function() {
io.sockets.emit('clear');
},60000);
io.sockets.on('connection', function (socket) {
socket.on('paint',function(data) {
socket.broadcast.emit('paint', data);
 
 
 
 
Search WWH ::




Custom Search