nowjs和nodejs实现服务器端与客户端实时数据传输的例子

参考:[url]http://www.bennadel.com/blog/2171-Realtime-Messaging-And-Synchronization-With-NowJS-And-Node-js.htm[/url]

先说例子实现的功能。网页上有一图片,图片可以拖动。用浏览器打开多个同一网页,当图片移动时,其它页面的图片会同步移动。例子也展示了用jQuery实现图片的拖动。
测试环境window7,nodejs v0.6.5 分别用ie,firefox,chrome打开[url]http://127.0.0.1:8080/client.html[/url],所有该网页上的图片会同步移动。贴上代码。
server.js端:
需要用sock.io和nowjs第三包,推荐用npm方式安装。nowjs包在window的安装可参考:
[url]http://blog.nowjs.com/running-nowjs-natively-on-windows[/url]
// 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 they can call
// when they want to sync the position of the draggable target.
// In the context of this callback, "this" refers to the
// specific client that is communicating with the server.
everyone.now.syncPosition = function (position) {//syncPosition()在这里定义,在客户端调用

// Now that we have the new position, we want to broadcast
// this back to every client except the one that sent it in
// the first place! As such, we want to perform a server-side
// filtering of the clients. To do this, we will use a filter
// method which filters on the UUID we assigned at connection
// time.
everyone.now.filterUpdateBroadcast(this.now.uuid, position);

};


// We want the "update" messages to go to every client except
// the one that announced it (as it is taking care of that on
// its own site). As such, we need a way to filter our update
// broadcasts. By defining this filter method on the server, it
// allows us to cut down on some server-client communication.
everyone.now.filterUpdateBroadcast = function (masterUUID, position) {

// Make sure this client is NOT the same client as the one
// that sent the original position broadcast.
if (this.now.uuid == masterUUID) {

// Return out of guard statement - we don't want to
// send an update message back to the sender.
return;

}

// If we've made it this far, then this client is a slave
// client, not a master client.
this.now.updatePosition(position);//updatePosition()为客户端定义的方法,在这里可调用,用this修饰now。

};

})();


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


// Write debugging information to the console to indicate that
// the server has been configured and is up and running.
sys.puts("Server is running on 8080");


我把重要的东西摘录下来:
[quote]Once the core HTTP server is configured and the NowJS module is initialized, we are given access to the "everyone" object. This everyone object then provides us with access to the server-side "now" scope. This "now" scope is shared between the server and every one of the clients. Anything added to or removed from the server-side "now" scope is also added to or removed from every client currently (or eventually) connected to the server.

This is true for both variables and functions! Notice that my server-side Node.js code defines two methods: syncPosition() and filterUpdateBroadcast(). By defining them in the "everyone.now" scope, I am making them available to both the server and to every single one of the connected clients.

But what about that, "everyone.now.updatePosition()", function? Where did that come from? Ah-ha! Here's the real, "there is no spoon" mind-screw - that function is defined on the client (which we'll see in a minute). And, since it's defined in the client's "now" scope, the server-side Javascript can then invoke it as if there were no separation between the server and client contexts.[/quote]

client.html
<!DOCTYPE html>
<html>
<head>
<title>NowJS And Node.js Realtime Communication</title>

<style type="text/css">

html,
body {
height: 100%;
overflow: hidden;
width: 100%;
}

img {
left: 9px;
position: absolute;
top: 70px;
}

</style>

<!-- We have this file stored explicitly. -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"/>
</script>

<!--
The NowJS HTTP augmentation will take care of routing
this - we don't actually have this physical file stored
at this file path.
-->
<script type = "text/javascript" src = "/nowjs/now.js" ></script>
</head>
<body>

<h1>
NowJS And Node.js Realtime Communication
</h1>

<!--
This will be draggable. When this image drags, we are
going to sync the position of it across browsers.
-->
<img
id="myhead"
src="./myhead.gif"
width="100"
height="100"
alt="It's my head, do you like it?"
/>


<!-- Configure the client-side script. -->
<script type="text/javascript">

// Get a reference to the target draggable.
var myhead = $("#myhead");

// Get a reference to the body - this is the element on which
// we'll be tracking mouse movement once the draggable
// tracking has been turned on.
var body = $("body");


// On mouse-down, turn on draggability.
myhead.mousedown(
function (event) {
// Prevent the default behavior.
event.preventDefault();

// Get the current position of the mouse within the
// bounds of the target.
var localOffset = {
x:(event.pageX - myhead.position().left),
y:(event.pageY - myhead.position().top)
};

// Start tracking the mouse movement on the body.
// We're tracking on the body so that the mouse can
// move faster than the tracking.
body.mousemove(
function (event) {
// Create a new position object.
var newPosition = {
left:(event.pageX - localOffset.x),
top:(event.pageY - localOffset.y)
};

// Update the target position locally.
myhead.css(newPosition);

// Announce the updated position so that we
// can sync accross all clients with NowJS.
now.syncPosition(newPosition);//syncPosition()是在服务器端定义的方法,可在客户端调用。
}
);
}
);


// On mouse-up, turn off draggability.
myhead.mouseup(
function (event) {
// Unbind the mousemove - no need to track movement
// once the mouse has been lifted.
body.unbind("mousemove");
}
);


// I allow the remove server to make a request to update the
// position of the target.
//
// NOTE: By defining this function in the NOW scope, it gives
// the server access to it as well.
now.updatePosition = function (newPosition){
//updatePosition()这个方法在客户端定义,可在服务器端调用
// Check to see if this client is in master mode; if so,
// we won't update the position as this client is
// actively updating its own position.
myhead.css(newPosition);

};

</script>
</body>
</html>


[quote]When the user moves the image on the client, the client broadcasts the new position using the "now.syncPosition()" function. This function, which was defined on the server, then pushes the updated position down to all the other clients using the "now.updatePosition()" function, which was defined on the client.

Even after coding this myself, it's still somewhat confusing; so, let's look at a quick rundown of the various functions to see where they were defined and where they were invoked:

[b]syncPosition()[/b]
[list]
[*]Defined: Server-side
[*]Invoked: Client-side
[/list]
[b]filterUpdateBroadcast()[/b]
[list]
[*]Defined: Server-side
[*]Invoked: Server-side
[/list]
[b]updatePosition()[/b]
[list]
[*]Defined: Client-side
[*]Invoked: Server-side
[/list][/quote]
NodeJS本地上传文件至服务器 立即下载

相关推荐

同花顺【红绿趋势】幅图指标 源码分析

a10:IF(差值<=0 ,0 ,差值*0.2 ,4 ,0),STICK,linethick5,colorred;a7:IF(差值<=0 ,0 ,差值*0.8 ,4 ,0),STICK,linethick5,colorred;a8:IF(差值<=0 ,0 ,差值*0.6 ,4 ,0),STICK,linethick5,colorred;a6:IF(差值<=0 ,0 ,差值*1 ,4 , 0),STICK,linethick5,colorred;DRAWICON(先锋<0,-25,1);

zhibiaogong的博客 4063

node.js学习笔记

node.js简介,node环境的安装,模块化规范,es6的模块化,fs模块,path,路由,form提交数据,querystring,ajax,npm,express,跨域访问,node接收前端请求参数,数据库,token

茹嗨瑞的博客 807

安卓逆向实战:用Batch Apktool 3.8.0快速汉化APK的完整流程

本文详细解析了如何使用Batch Apktool 3.8.0进行安卓APK汉化的完整流程,包括环境配置、反编译、资源解析、深度汉化、重构建与签名优化等关键步骤。通过这款集成化逆向工具,开发者可以高效完成APK汉化,提升工作效率。

s1t2u3的博客 1099

进入nodejs 利用http模块搭建一个简单的服务器并配合fs模块网客户端传输文件

这里我们只用fs.readFile()方法,他有两个参数,第一个参数为读取文件的路径;node.js是一个软件,它是js的代码运行环境,可以运行js代码然后实现服务器的功能;到此一个简单的服务器就搭建完成了,还未介绍createServer()方法中回调函数的两个参数,相信大家有点不清楚。解析node就是去环境变量中找到这个node变量指向的软件,然后用node.exe这个软件去运行这个js文件。想要实现服务器的功能,就离不开http模块,它是node自带的模块,这个模块有一个函数可以创建服务器。...

m0_59345890的博客 675

[3D检测系列-PV-RCNN] PV-RCNN实战指南:从论文解析到代码调试全流程

本文提供了PV-RCNN在3D目标检测领域的实战全流程指南。文章深入解析了其Point-Voxel融合的核心思想,并详细演示了从环境搭建、数据准备、代码复现到模型训练与调试的具体步骤,特别针对常见的报错问题给出了解决方案,帮助开发者高效掌握这一经典算法。

weixin_29189381的博客 480

国产化软件设计:遵循信创要求,助力信息技术自主创新

支持国产操作系统、CPU、数据库和中间件。确保网络通信的身份鉴别、数据传输机密性和完整性。实现应用和数据层的身份鉴别、数据传输机密性完整性、数据存储机密性完整性。依托法院密码服务平台提供的商用密码能力。

qq_41186565的博客 3372

node.js 的构建工具_如何使用Node.js和Now构建电报机器人

node.js 的构建工具 介绍 ( Introduction ) Serverless deployment, the intriguing topic grabbing a lot of attention from rookies and veterans alike in the tech ecosystem is finally here. In this article we'll b...

culiu9261的博客 591

innovus: 如何让两个generate clock balance skew group?

如题,在sdc约束中两个generate clock被设置到同一个clock group中,工具虽然会生成对应的两个skew group,但是阅读ccoot_spec发现工具并没有让两个skew group进行balance,这时就需要手动设置balance skew group。我正在「拾陆楼」和朋友们讨论有趣的话题,你⼀起来吧?

m0_61544122的博客 4049

nodejs之时间、时间戳

*******一共有5中方法(执行效率依次降低): Date.now(); new Date().getTime(); new Date(); process.uptime(); process.hrtime(); Date.now()、new Date().getTime() 和 new Date() 是浏览器环境下一直都有; process.uptime() 返回的是Node程序已运行的时间,单位秒。 process.hrtime() 返回的是当前的高分辨率时间,格式为[秒, 纳秒]。它是相.

u010227042的博客 5532

多模态目标检测综述介绍及框架提供

多模态目标检测是计算机视觉领域的前沿方向,旨在通过融合不同传感器或数据源的信息(如可见光、红外、深度等),提升复杂场景下目标检测的准确性和鲁棒性。

Limiiiing的博客 4588

《MPDIoU:边界框回归的高效革新与YOLOv8集成实战指南》

摘要: MPDIoU(多优先级距离IoU)通过引入中心距离、形状差异和尺度变化的三步优化策略,解决了传统IoU在目标检测中的尺度敏感、收敛低效和场景局限问题。相较于GIoU、DIoU等主流方法,MPDIoU在精度、速度和鲁棒性上实现全面提升,尤其在复杂场景和小目标检测中表现突出。通过代码集成和训练优化,MPDIoU在YOLOv8中显著提升COCO数据集AP指标,并在智能安防(密集行人检测)和工业质检(微小缺陷定位)等垂直领域验证了其应用价值。未来研究方向包括动态权重调整和多模态融合,进一步拓展边界框回归的精

m0_64661770的博客 159

Nodejs学习——动态实时更新vue的数据

~

m0_37876745的博客 764

⭐️VMwareWorkstation17.0虚拟机安装搭建Windows 7虚拟机(完整图文详细步骤含配置VMware Tools教程)

本教程为大家提供了从安装VMware Workstation 17.0开始,到在虚拟机上成功搭建Windows 7专业版系统的完整步骤。我们详细介绍了准备阶段所需的软件和硬件要求,以及在VMware中配置和安装Windows 7系统的每一步操作。此外,我们还特别提到了如何在虚拟机上配置VMware Tools,以便更好地与宿主机进行交互。 通过本教程的学习,读者不仅能够掌握在VMware Workstation 17.0上安装Windows 7虚拟机的技能,还能了解到如何配置虚拟机的硬件以及安装VMwar

Python老吕的博客 2万+

Node.js 由服务端发送渲染页面到客户端

var template = require('art-template'); var http = require('http'); var Fs = require('fs'); var Server = http.createServer(); Server.on('request',function(request,response){ var url = request.url; if(url === '/render'){ /* 1.读取相应html文件, 并用模板引擎完

Vodka的博客 320

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

nodejs实现Websocket的数据接收发送

  在去年的时候,写过一篇关于websocket的博文:http://www.cnblogs.com/axes/p/3586132.html,里面主要是借助了nodejs-websocket这个插件,后来还用了socket.io做了些demo,但是,这些都是借助于别人封装好的插件做出来的,websocket到底是怎么实现的呢自己之前真没怎么去想过,最近在看朴灵大神的《深入浅出nodej...

dfpbut5000的博客 1293

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

使用Nodejs实现实时推送MySQL数据库最新信息到客户端

下面我们要做的就是把MySQL这边一张表数据的更新实时的推送到客户端,比如MySQL这边表的数据abc变成123了,那使用程序就会把最新的123推送到每一个连接到服务器的客户端。如果服务器的连接的客户端为0,也就是这时候没有客户端连接,那程序也不会执行推送信息的代码以免产生不必要的资源消耗,当有客户端连上的时候又开始推送。demo的代码大家可以到下面的Download按钮去下载。 ...

anaijiao0225的博客 375

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

nodejs 使用socket.io与网页实时数据交互

首先我们需要安装socket模块 安装命令: npm install socket.io 编辑前台页面:index.html 统计在线人数 // 创建websocket连接 var socket = io.connect('http://localhost:3000'); // 把信息显示到

咖啡如同生活的专栏 6136

Nodejs实现websocket 数据实时更新 适用h5(模拟数据,不需要数据库)

1.先建立一个node 后台服务 2. 建立socket项目; 实时通讯,而WebSocket无疑是最合适的。WebSocket相较于HTTP来说,有很多的优点,主要表现在WebSocket只建立一个TCP连接,可以主动推送数据到客户端,而且还有更轻量级的协议头,减少数据传送量。所以WebSocket暂时来说是实时通讯的最佳协议了。   至于服务器语言选择nodeJs,一是因为自己是做前端的...

IT博客技术分享 3239

Node.js 获取当前时间

node.js 获取当前时间

qq_37962440的博客 7562

nodejs实现数据流传输demo

摘要nodejs实现数据流传输demo,分为服务端(接受数据)和客户端(发送数据)。 server端代码 var http=require("http"); var querystring = require('querystring'); ​ var server=new http.Server(); consol...

Harry Wong的博客 831

nodejs客户端与服务器双向数据交换

情景交互:当客户端发送ping请求到服务器的时候,服务器响应pong。服务器发送ping请求到客户端的时候,客户端响应pong。 var http = require('http'); var fs = require('fs'); var server = http.createServer(function (req, res) {   fs.readFile('./index.htm

跟我一起去征服 3273

nodejs服务器与服务器之间通讯问题(nodejs服务器端创建客户端)

nodejs服务器与服务器之间通讯问题(nodejs服务器端创建客户端)相信很多开发人员都遇到过服务器主动和其他服务器建立连接的需求。 下面给大家整理了三种在服务器建立客户端的代码,希望能够帮助到您!下面只是关键代码,请自行修改运行逻辑 net模块创建客户端/**net在服务器端创建客户端*/ var net = require('net');var client = new net.Socket

li18883754474的博客 6007

用node.js(socket.io)实现数据实时推送

转载自:  http://xiaocaicode.lofter.com/post/cf1f9_7b6507?mydomainr=true     用node.js(socket.io)实现数据实时推送   在做商品拍卖的时候,要求在商品的拍卖页面需要实时的更新当前商品的最高价格。实现的方式有很多,比如: 1.setInterval每隔n秒去异步拉取数据(缺点:更新不够实时) 2...

sifeimeng的专栏 518

nodejs中tcp服务器的搭建和客户端通信的实现

nodejs中如何实现服务器和客户端的通信,以及tcp服务器的搭建和客户端的搭建问题,下面结合自己的实例来分享下 工具/原料 nodejs+sublime+win7 方法/步骤 首先,创建tcp服务器,创建的方式如下面图中所示,先创建一个net服务,然后监听connect和data事件,并对收到的数据进行确认,监听端口

hanyingzhong的专栏 2246
上一篇: 用socket.io实现WebSocket的一个简单例子
下一篇: nodejs运行coffeescript
biyeah
博客等级 码龄24年 0粉丝 40原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值