Node.js 和 Socket.io 入门教程

安装Nodejs:

nodejs有自己的包管理工具,叫npm,通过npm管理依赖包,相当的方便。安装nodejs也是比较方便,Ubuntu上直接用:

apt-get install nodejs

Debian系统:

Node.js在官方的Debian Sid(unstable).中已经有了,可以直接通过apt-get安装,首先检查apt-get的source文件/etc/apt/source.list中是不是已经包含

deb http://ftp.us.debian.org/debian/ sid main

可以通过如下方式安装:

root@host: ~ # echo deb http://ftp.us.debian.org/debian/ sid main > /etc/apt/sources.list.d/sid.list
root@host: ~ # apt-get update
root@host: ~ # apt-get install nodejs

详细的安装信息这里有: https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager

安装Socket.io:

开发Node.js程序当然离不开Socket.io,安装Socket.io也是比较的简单:
Ubuntu系统,先安装npm包:

apt-get install npm

安装npm包后,就可以通过npm包安装Socket.io了:

npm  install socket.io

开发入门:

socket.io主页上有不少的例子,这里是自己整理的一个例子,服务器每隔2秒向客户端发送一条消息的例子:

Server: server.js

var app = require('http').createServer(handler),
    io = require('socket.io').listen(app),
    fs = require('fs');

app.listen(8080);
function handler (req, res) {
      fs.readFile(__dirname + '/index.html',
      function (err, data) {
        if (err) {
          res.writeHead(500);
          return res.end('Error loading index.html');
        }
        res.writeHead(200);
        res.end(data);
      });
}

io.sockets.on('connection', function (socket) {
        io.sockets.emit('news',  'welcome to nodejs');
     var tweets = setInterval(function () {
      socket.emit('news', 'bieber tweet ok');
      }, 2000);

      socket.on('disconnect', function () {
        clearInterval(tweets);
        io.sockets.emit('user disconnected');
      });
});

Client: index.html

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost/');
  socket.on('news', function (data) {
      console.log(data);
      $("#alarm").append(data).append('<br/>');
    socket.emit('my other event', { my: 'data' });
  });
</script>
</head>
<body>
    <div id="alarm"></div>
</body>
</html>

server.js和index.html放到同一个目录下,然后启动:

> node server.js

在浏览器上访问: http://127.0.0.1:8080/ 即可看到客户端不断的有数据更新。