服务器时间和客户端时间 – 差异?

我已经写了一个代码,告诉我一个数据包从server to client花费的时间,以及从client to server to client总时间。 这是我的代码。

客户端:

 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ping</title> <script src="/socket.io/socket.io.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> $(document).ready(function(e) { var socket = io.connect('http://pingme.jit.su:80/', {secure: false}); $('#button').click(function(e) { e.preventDefault(); $(this).attr('disabled','disabled'); var time = (new Date()).getTime(); socket.emit('ping', time); }); socket.on('pong', function(data) { var time2 = (new Date()).getTime(); var lat = time2 - data.server; var roundtrip = time2 - data.init; var str = '<br><br><strong>From Server</strong>: '+lat+' ms<br><strong>Roundtrip</strong>: '+roundtrip+' ms<br><br>'; $('#res').prepend(str); $('#button').removeAttr('disabled'); }); }); </script> </head> <body style="margin:0;"> <input type="button" name="Button" id="button" value="Latency"> <div id="res"></div> </body> </html> 

服务器端:

 var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') , path = require('path') , url = require("url") , querystring = require("querystring"); app.listen(8080); io.configure('development', function(){ io.set('transports', ['xhr-polling']); }); io.configure('production', function(){ io.set('transports', ['xhr-polling']); }); var static = require('node-static'); var fileServer = new static.Server('.', { cache: false }); function handler (request, response) {   var pathname = url.parse(request.url).pathname; if(pathname == '/') { pathname = '/app.html'; } request.addListener('end', function () { fileServer.serveFile(pathname, 200, {}, request, response, function(err, result) { if(err) { console.log(err); console.log(err.status); } else console.log(result); }); }); } io.sockets.on('connection', function (socket) { socket.on('ping',function(data) { var time = (new Date()).getTime(); socket.emit('pong', {server:time, init:data}); }); }); 

这个问题很好地在本地显示以下输出:

 From Server: 4 ms Roundtrip: 11 ms From Server: 10 ms Roundtrip: 15 ms 

当我在Nodejitsu上部署后运行时,会得到exception的结果。 它给了我以下输出:

 From Server: 2223 ms Roundtrip: 956 ms From Server: 2265 ms Roundtrip: 915 ms 

怎么可能这个数据包需要更多的时间从服务器传输而不是整个往返? 我认为这是由于服务器和客户端之间的时间差异造成的。 你觉得它是什么?

发生这种情况有很多原因。 但是如果你想testing你的编程,那么你应该比较结果像traceroute(在Linux上的命令)。

事情总是在本地更快地进行。 当你访问局域网之外的东西时,你会得到各种开销和延迟。

一个简单的traceroute可能会解释很多。 另外,你可以从这里做到这一点:

http://www.traceroute.org/

//编辑//

有很多方法可以做到这一点,检查这个链接:

浏览器的延迟/ Pingtesting

但基本的原则是,你发送多个消息。 您可以使用您的第一个请求 – 响应消息来计算出时间。 我跟1000个客户做了这个,我做的是跟踪每个人的情况。 一旦你计算出偏移量(即客户端比服务器提前1小时),那么你可以从你的延迟计算中减去它。 看看这个PHP函数

http://php.net/manual/en/function.timezone-offset-get.php

这应该至less有助于指引你正确的方向:) – 让我知道如果你需要更多的帮助。