我想在Angular中计算下载和上传网速.
对API的请求不是最佳解决方案,因为如果服务器本身从加载速度变慢,结果将是不正确的.
也许Angular有解决方案,它使用特殊网站(例如speedtest.net).
有任何想法吗?
什么是互联网速度?
每个人都希望下载越来越快,并且还能更快地上传文件.但是这是什么意思?当您下载或上传某些内容时,您和服务器正在以特定方式进行通信.您有两个互联网连接,但在大多数情况下,您的速度比服务器连接慢.要理解这一点,只需遵循以下逻辑:
您正在与其他数千名用户一起玩一些视频游戏.您(和其他玩家连接)每秒可以发送和接收20个单位.服务器每秒最多可发送200万个单元.通过这种方式,每个人都很开心并且在线.如果服务器每秒只能发送20个单元,那么每个人都会落后,甚至最差(比如丢包).
因此,要回答互联网速度是什么,从发送给您的请求到前往服务器的时间是否有响应,然后将其转回给您.当然,如果服务器已关闭或已完成其单位空间专用于您,您的请求将被延迟,但这是互联网的工作方式.
当您下载或流式传输电影时,它会发生同样的事情:每次下载/流式传输一小部分时,您都在请求新的块.
我们来谈谈一些数字
时间在互联网上被误导,以毫秒为单位.如果你只是打开一个终端并做一个简单的ping www.stackoverflow.com事情就会有类似的东西:
Reply from 151.101.1.69: bytes=32 time=36ms TTL=56
Reply from 151.101.1.69: bytes=32 time=36ms TTL=56
Reply from 151.101.1.69: bytes=32 time=36ms TTL=56
Reply from 151.101.1.69: bytes=32 time=36ms TTL=56
Run Code Online (Sandbox Code Playgroud)
这time=36ms是您发送ping请求和请求支持之间传递的时间.
到底
我希望在网上清除所有内容,测量时间,就像这样:
- Start couting
- Send a request
- ...
- Wait..
- ...
- Request turned back
- Stop Counting
Run Code Online (Sandbox Code Playgroud)
**但我的问题是:我可以角度来做吗?**
答案是..有点.可能有更好的方法可以做到这一点,但几个月前我也想这样做,我想出了这个想法.
假设我们有一个服务来执行请求:
export class MyService{
constructor(
private http: Http
)
public sendRequest(){
return this.http.get(...something);
}
}
Run Code Online (Sandbox Code Playgroud)
我们的主要组件将有服务注入,并将计算时间过去:
export class MyComponent{
public timePassed: any;
constructor(
private service: MyService
)
ngOnInit(): void{
const startingTime = new Date().getTime();
this.service.sendRequest()
.subscribe( res => {
this.timePassed = ((new Date() - startingTime).getTime())/1000;
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在您的timePassed变量中,您将获得请求所花费的时间.正如我所说,由于连接速度缓慢或服务器连接速度缓慢,时间可能会发生变化.
你总是要像互联网速度一样思考两个人互相交谈.总是.如果你不能将你的速度与别人的速度联系在一起,那么谈论速度是没有意义的.
如果你想使用第三方 API,有一些专门的速度测试网站,它们也提供 API 访问。例如:
您可以在此处查看相关的 SO 答案。
或者
如果你想在 Angular 中自己实现它,你可以查看我的存储库。我前段时间这样做是为了测试下载速度:angular-speed-test。
我使用 Angular HttpClient 进度事件来跟踪数据传输并基于此计算速度。
服务代码:
import { Injectable } from "@angular/core";
import { HttpClient, HttpRequest } from "@angular/common/http";
@Injectable({
providedIn: "root"
})
export class FileDownloaderService {
url: string = "some file path for download";
constructor(private http: HttpClient) {}
download() {
const req = new HttpRequest("GET", this.url, {
responseType: "blob",
reportProgress: true
});
return this.http.request(req);
}
}
Run Code Online (Sandbox Code Playgroud)
组件:
import { Component } from "@angular/core";
import { HttpClient, HttpEventType, HttpResponse } from "@angular/common/http";
import { FileDownloaderService } from "./file-downloader.service";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
constructor(
private http: HttpClient,
private downloader: FileDownloaderService
) {}
percentDone: number;
startTime: any;
endTime: any;
currTime: any;
prevTime: any;
speed: number = 0;
bytesReceied: number = 0;
oldbytes: number = 0;
unit: string = "Mbps";
download() {
this.downloader.download().subscribe(event => {
if (event.type === HttpEventType.DownloadProgress) {
//tracking percent received and how much time has passed
this.percentDone = Math.round((100 * event.loaded) / event.total);
this.currTime = new Date().getTime();
//setting start time
if (this.percentDone === 0) {
this.startTime = new Date().getTime();
this.prevTime = this.startTime;
}
//tracking how much data is received
this.bytesReceied = event.loaded / 1000000;
//calculating download speed per percent data received
this.speed =
(this.bytesReceied - this.oldbytes) /
((this.currTime - this.prevTime) / 1000);
if (this.speed < 1) {
this.unit = "Kbps";
this.speed *= 1000;
} else this.unit = "Mbps";
//updating previous values
this.prevTime = this.currTime;
this.oldbytes = this.bytesReceied;
//calculating avg download speed
if (this.percentDone === 100) {
this.endTime = new Date().getTime();
let duration = (this.endTime - this.startTime) / 1000;
let mbps = event.total / duration / 1000000;
if (mbps < 1) {
this.speed = event.total / duration / 1000;
this.unit = "Kbps";
} else {
this.speed = mbps;
this.unit = "Mbps";
}
}
}
//download file
else if (event instanceof HttpResponse) {
var res: any = event.body;
var url = window.URL.createObjectURL(res);
var a = document.createElement("a");
document.body.appendChild(a);
a.setAttribute("style", "display: none");
a.href = url;
a.download = "SpeedTest_32MB.dat";
a.click();
window.URL.revokeObjectURL(url);
a.remove();
console.log("File is completely downloaded!");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2384 次 |
| 最近记录: |