我写了一个代码,它告诉我一个数据包到达的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 上部署后运行时出现异常结果。它给了我以下输出:
From Server: 2223 ms
Roundtrip: 956 ms
From Server: 2265 ms
Roundtrip: 915 ms
数据包从服务器传输到整个往返所需的时间怎么可能比整个往返时间更长?我认为这是由于服务器和客户端之间的时间差异。你认为那是什么?