Cuttlepress

Blogging about Hacker School?

Day 28

I spent a fair amount of time today showing off some technologies to other folks: Julia and I went over some of my past Flixel and Box2D games, and Lyndsey and I investigated various methods of casting on. (The latter is knitting, not code, of course.)

I also put together a working demonstration of communication both to and from the server using WebSocket, with help from Julia and Kate. I continue to be unimpressed by the Socket.io docs, which seem to be designed to make the user feel inept.

Here’s some server code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var http = require('http')
  , express = require('express')
  , app = express()
  , port = process.env.PORT || 5000;

var server = http.createServer(app);
server.listen(port);

var io = require('socket.io').listen(server);

io.sockets.on('connection', function(socket){
  socket.on('mouseMoved', function(mouseX, mouseY){
      socket.broadcast.emit('mouseMoved', mouseX, mouseY);
      socket.emit('mouseMoved', mouseX, mouseY);
  });
});

And here’s the client side (after initializing the canvas and setting default variable values and such):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function draw() {
  ctx.clearRect(0,0,canvas.width, canvas.height);
  ctx.fillStyle = "ff0000";
  ctx.fillRect(otherMouseX-5,otherMouseY-5,10, 10);
}

function  mouseMoved(e) {     //e is the event handed to us
    mouseX = e.pageX - canvas.offsetLeft;
    mouseY = e.pageY - canvas.offsetTop;
    ws.emit("mouseMoved", mouseX, mouseY)
}

var ws = io.connect('http://localhost:5000/')

ws.on('mouseMoved', function(mouseX, mouseY){
  otherMouseX = mouseX;
  otherMouseY = mouseY;
})

The result is magically linked canvases: move around in one window, and the square cursor in the other window moves to follow.

Magic canvases!