Real time mouse activity w/ NodeJS & Sockets

Quick link to the NodeJS/websocket game I made — includes source

Thanks to Reddit for helping me test this.

Steps:
Get NodeJS
Get npm
Get SocketIO

Create server.js
Paste in:

// Simple Node & Socket server

var http = require('http')
  , url = require('url')
  , fs = require('fs')
  , io = require('../')
  , sys = require('sys')
  , server;

server = http.createServer(function(req, res){
  var path = url.parse(req.url).pathname;
  switch (path){
    case '/':
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
      res.end();
      break;
      
    case '/json.js':
    case '/test.html':
      fs.readFile(__dirname + path, function(err, data){
        if (err) return send404(res);
        res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
        res.write(data, 'utf8');
        res.end();
      });
      break;
    default: send404(res);
  }
}),

send404 = function(res){
  res.writeHead(404);
  res.write('404');
  res.end();
};
server.listen(8080);

// socket.io, I choose you
var io = io.listen(server)
  , buffer = [];
  
io.on('connection', function(client){
  client.send({ buffer: buffer });
  client.broadcast({ announcement: client.sessionId + ' connected' });
  
  client.on('message', function(message){
    var msg = { message: [client.sessionId, message] };
    buffer.push(msg);
    if (buffer.length > 15) buffer.shift();
    client.broadcast(msg);
//    console.log(msg);
});
  client.on('disconnect', function(){
    client.broadcast({ announcement: client.sessionId + ' disconnected' });
  });
});

Create test.html
Paste in:

<!doctype html>
<html>
  <head>
    <title>Multi Mouse - How many mice can I mouse eater eat?</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <!-- jquery -->        
    <script src="/json.js"></script> <!-- for ie -->
    <script src="socket.io/socket.io.js"></script> <!-- sockets -->
  </head>
  <body>
<h1> You can see my mouse!! ZOMG - <a href="http://www.youtube.com/watch?v=aFLcbBvTGns">Video explaining why I'm doign this</a></h1>    

    <script>

// some random color 
function randc(){
colors = new Array('#FF0000','#00FF00','#0000FF','#00FFFF','#FF00FF','#C0C0C0');
var color = colors[Math.floor(Math.random()*colors.length)]
return color;
}

// When a new message arrives..
      function message(obj){
	var data = obj.message[1].split(':');
	var x = data[0];
	var y = data[1];
        var userid = obj.message[0];

  if($('#mouse_'+userid).length == 0 && userid != 'you') {
	var randcolor = randc();
	$('body').append('<div class="dot" style="background-color:'+randcolor+'" id="mouse_'+userid+'"/>'
    );
  }

// stops a dot being drawn for local user
if (userid != 'you'){
   $('#mouse_'+userid).css({
    'left' : x + 'px',
    'top' : y + 'px'
  })
}
        var el = document.createElement('p');
        if ('announcement' in obj) el.innerHTML = '<em>' + esc(obj.announcement) + '</em>';
        else if ('message' in obj) el.innerHTML = '<b>' + esc(obj.message[0]) + ':</b> ' + esc(obj.message[1]);
        document.getElementById('chat').appendChild(el);
        document.getElementById('chat').scrollTop = 1000000;
      }
      
// A function to define how we send data
      function send(){
        var val = document.getElementById('text').value;
        socket.send(val);
        message({ message: ['you', val] });
        document.getElementById('text').value = '';
      }
      
// When a mouse is moved
      window.onmousemove = function(event){
	 message({ message: ['you', event.clientX+':'+event.clientY] });
         socket.send(event.clientX+':'+event.clientY);
      };

// replace <&> w/ &lt&&gt
      function esc(msg){
        return msg.replace(/</g, '&lt;').replace(/>/g, '&gt;');
      };

// establish the socket connection      
      var socket = new io.Socket(null, {port: 8080, rememberTransport: false});
      socket.connect();
      socket.on('message', function(obj){
        if ('buffer' in obj){
          document.getElementById('form').style.display='none';
          document.getElementById('chat').innerHTML = '';
          
          for (var i in obj.buffer) message(obj.buffer[i]);
        } else message(obj);
      });
    </script>
    
    <div id="chat"><p>Connecting...</p></div>
    <form id="form" onsubmit="send(); return false">
      <input type="text" autocomplete="off" id="text"><input type="submit" value="Send">
    </form>
    
    <style>
      .dot { height: 10px; width: 10px; background-color:#000000;position:absolute;left:0;top:0;}
    </style>
    
  </body>
</html>

Run it with

node server.js

Test it by visiting http://whatever:8080

Quick link to the NodeJS/websocket game I made — includes source

Profanity filtering in AjaxChat

AjaxChat provide a Client side profanity filter but this is not cool because:

a) Big arrays of profanities on your client is going to kill javascript
b) You are going to be passing your users an array of profanities.

Fix? Do it server side. giggidy. Jump into /ajaxchat/lib/class/AJAXChat.php

Just above the insertCustomMessage function add

 function filterMessageText($text){
    $prof = array("badword1","badword2"); // extend this with your bad words..
    $replace = array();
    foreach ($prof as $word){
       $replace[] = str_repeat('*', strlen($word));
    }
    return str_ireplace($prof, $replace, $text);
  }

Go to line 1498 and add:

// Copies the original text to a value we can store in a separate table if we want to.
   $original_text = $text;
// Pass the text through the filter.
          $text = $this->filterMessageText($text);

npm install ReferenceError: console is not defined

Trying to install npm with:

curl http://npmjs.org/install.sh | sh

Returns:

ReferenceError: console is not defined:

Cause:
NodeJS not properly installed.

Solution:
Goto NodeJS download and get the latest tar package and install it yourself. Usual install procedure:

tar -zxvf node-whatever.tar.gz
cd node-whatever
./configure
make
make install

Now try again and it should work 🙂

Would a “kinnected” classroom damage the OLPC goal

The Microsoft Kinect device has various practical uses in the classroom. I have blogged about it a few times but some thinking today has made me question if the focus we should have in a classroom is towards many to one or if we should be putting more focus and investment into OLPC.

I was thinking if you were given a choice to control the teachers white board would you rather do it with a device in front of you or would you rather do it with some sort of augmented control on your desk/in the air?

One to many or many to one?

I think that personalized learning dictates each child should have their own device but that only really currently makes sense if the kids have learned fine motor skills to control the devices.

Story telling etc. can receive additional immersion with real time physical space feedback. That is where the Kinect comes into it’s own IMHO.. Before any Apple fan girls start moaning that I’m jumping on the MS bandwagon I think you should remember that I’m talking about the Kinect like it is the only space aware tool available because IT IS. The depth perception market isn’t an iPod style market where Apple out-market Sony even though there product is inferior. If there were other options I would be considering them.

Problems with space

The huge problem is that Kinect requires a huge amount of physical space in the room for the user. Sure it can handle 2 or 3 people but it would struggle to differentiate between different users(pupils) in a reception/nursery class.

So where does a Kinect style control fit in?

Are classrooms too small?  Various Educational Technology Leaders are currently experimenting with it’s place in the classroom.  Consolarium up in Scotland powered by the mighty Derek Robertson are doing some fantastic things and I’m looking forward to their feedback.

Is the Kinect unable to differentiate between enough users?  I think this is more likely the case.  So if it could that would be awesome..

Is 1 kinect per child an unrealistic expecation?

Of course it is, initially..  But in the future when Kinect type technology is included with OLPC why not consider the entire desk space virtual space?  How about multiple kinects in a classroom (one in each corner) being able to compute 3d space.  With this type of connectivity the kinect could figure out which desk a pupil is at and turn that desk into a control mechanism to either a) collaborate with the teacher on the IWB or to collaborate with other pupils…

What is the likely first step for Kinect outside of the XBOX world?

I have given the PT Installs team a budget to develop a new product that is useful for EYFS as we think that is the initial location where the Kinect plugged into a PC will be most fruitful.   We want to move away from the console lock ins for various obvious reasons.   I can’t say for obvious political reasons what our first project will be but expect to see something in and around the 2013/14 period.

I would expect the initial cost to be around the £500 mark which is roughly the cost of 2 devices per child and should (in theory) be able to leverage a large amount of content already available on the market.

So will a “kinnected” classroom damage the OLPC goal?

In theory it should aid it by giving kids a more natural way of interacting and becoming confident with using technology.

Enhanced by Zemanta

10 useful free services for UK Primary School ICT Co-ordinators

In 2010 I worked on a bucket load of free projects that should be useful for ICT leaders in Primary Schools. Here they are..

1. Important Dates – A simple way to find out any important events coming up in the UK.

2. Satpin – Satpin is a simple way to share links with KS1 children. That is all. No fuss, no hype.

3. Primary School TV – The easy way to find and watch TV / video clips in your classroom. Primary School TV has over 1 million videos specifically filtered from youtube, bbc iplayer, bbc learningzone, howthingsworks and more!

4. ICT Freebies Mailing list – Join 4000+ other ICT co-ordinators and get your weekly free ICT service here!

5. Primary Games Arena – The easiest way to find a suitable Game to support your pupils learning.

6. Primary School Blog Feed – Looking for inspiration for how to get started blogging? Just steal/borrow ideas from other schools. Don’t worry, we won’t tell anyone 🙂 If you want to get started blogging you might want to check out PrimaryBlogger

7. My School Holidays – Looking for your school holiday dates and want an easy way to share them?

8. Searchypants – Looking for a way to increase your e-Safety whilst promoting the image of your school and easily sharing links to websites?

9. Safe Search – Safe Search engine for Primary school relevant Video, Games, Websites and Images used by 8000 schools worldwide.

10. Classdroid – The easiest way to record pupil assessment, this app is for Android devices and is currently in its infancy.

11. ICT Leaders blogs. Okay so I went over 10. Whoops. Ever wondered what other Primary School ICT leaders are up to? This is a collection of all of the known ICT leaders blogs.

12. Yipes.. I forgot another great one.. This list of great free web2 alternatives for primary schools should help you find a web based free alternative to applications such as Microsoft Word and other germs.

That’s all folks.. Enjoy!