日期:2014-05-16  浏览次数:20289 次

nowjs和nodejs实现服务器端与客户端实时数据传输的例子
参考:http://www.bennadel.com/blog/2171-Realtime-Messaging-And-Synchronization-With-NowJS-And-Node-js.htm

    先说例子实现的功能。网页上有一图片,图片可以拖动。用浏览器打开多个同一网页,当图片移动时,其它页面的图片会同步移动。例子也展示了用jQuery实现图片的拖动。
测试环境window7,nodejs v0.6.5 分别用ie,firefox,chrome打开http://127.0.0.1:8080/client.html,所有该网页上的图片会同步移动。贴上代码。
server.js端:
需要用sock.io和nowjs第三包,推荐用npm方式安装。nowjs包在window的安装可参考:
http://blog.nowjs.com/running-nowjs-natively-on-windows
// Include the necessary modules.
var sys = require("util");
var http = require("http");
var url = require("url");
var path = require("path");
var fileSystem = require("fs");


// ---------------------- //
// ---------------------- //


// Create an instance of the HTTP server.
var server = http.createServer(
    function (request, response) {

// Get the requested "script_name". This is the part of the
// path after the server_name.
        var scriptName = request.url;

// Convert the script name (expand-path) to a physical file
// on the local file system.
        var requestdFilePath = path.join(process.cwd(), scriptName);

// Read in the requested file. Remember, since all File I/O
// (input and output) is asynchronous in Node.js, we need to
// ask for the file to be read and then provide a callback
// for when that file data is available.
//
// NOTE: You can check to see if the file exists *before* you
// try to read it; but for our demo purposes, I don't see an
// immediate benefit since the readFile() method provides an
// error object.
        fileSystem.readFile(
            requestdFilePath,
            "binary",
            function (error, fileBinary) {

// Check to see if there was a problem reading the
// file. If so, we'll **assume** it is a 404 error.
                if (error) {

// Send the file not found header.
                    response.writeHead(404);

// Close the response.
                    response.end();

// Return out of this guard statement.
                    return;

                }

// If we made it this far then the file was read in
// without a problem. Set a 200 status response.
                response.writeHead(200);

// Serve up the file binary data. When doing this, we
// have to set the encoding as binary (it defaults to
// UTF-8).
                response.write(fileBinary, "binary");

// End the response.
                response.end();

            }
        );

    }
);

// Point the server to listen to the given port for incoming
// requests.
server.listen(8080);


// ---------------------- //
// ---------------------- //


// Create a local memory space for further now-configuration.
(function () {

// Now that we have our HTTP server initialized, let's configure
// our NowJS connector.
    var nowjs = require("now");


// After we have set up our HTTP server to serve up "Static"
// files, we pass it off to the NowJS connector to have it
// augment the server object. This will prepare it to serve up
// the NowJS client module (including the appropriate port
// number and server name) and basically wire everything together
// for us.
//
// Everyone contains an object called "now" (ie. everyone.now) -
// this allows variables and functions to be shared between the
// server and the client.
    var everyone = nowjs.initialize(server);


// Create primary key to keep track of all the clients that
// connect. Each one will be assigned a unique ID.
    var primaryKey = 0;


// When a client has connected, assign it a UUID. In the
// context of this callback, "this" refers to the specific client
// that is communicating with the server.
//
// NOTE: This "uuid" value is NOT synced to the client; however,
// when the client connects to the server, this UUID will be
// available in the calling context.
    everyone.connected(
        function () {
            this.now.uuid = ++primaryKey;
        }
    );


// Add a broadcast function to *every* client that