はじめてのSocket.IO

既に3回ほどは書いた覚えのあるSocket.IOを使ったコードを書いてみたりしてみました。

index.html
<!DOCTYPE html>
<meta charset="utf-8">
<title>Socket.IO test</title>
<script src="/socket.io/socket.io.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
  var socket = io.connect();

  socket.on('connection', function(data) {
    console.log('connection');
    console.log(data);
  });
  
  socket.on('button1', function(data) {
    console.log('button1 event');
    console.log(data);
  });
  
  socket.on('button2', function(data) {
    console.log('button2 event');
    console.log(data);
  });
  
  document.getElementById('button1').addEventListener('click', function() {
    socket.emit('server button1 event');
  }, false);
  document.getElementById('button2').addEventListener('click', function() {
    socket.emit('server button2 event');
  }, false);
}, false);
</script>
<button id="button1">button 1</button>
<button id="button2">button 2</button>
index.js
var fs = require('fs'),
    http = require('http'),
    sio = require('socket.io'),
    server = http.createServer(),
    io = sio.listen(server);

io.configure('development', function() {
  io.set('transports', ['websocket']);
});

io.sockets.on('connection', function(socket) {
  socket.on('server button1 event', function() {
    socket.emit('button1', {
      button1: 1
    });
  });

  socket.on('server button2 event', function() {
    socket.emit('button2', {
      button2: 2
    });
  });
  
  socket.emit('connection', function() {
    socket.emit('connection', {
      message: 'connection!'
    });
  });
});

server.on('request', function(req, res) {
  if (req.url !== '/') {
    res.writeHead(307, {
      Location: '/'
    });
    res.end();
    return;
  }
  fs.readFile(__dirname + '/index.html', function(err, data) {
    if (err) {
      res.writeHead(500);
      res.end('Error loading index.html');
      return;
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    });
    res.end(data);
  });
});
server.listen(3000);

動作させる

$ npm install socket.io
$ node index.js


前はよくわからないまま書いてたけど、今なら理解してるはずなので(細かいところは知らないけど)なにかこのまま作れそうな気がする。