From 85363d47653592b007de803d567a913f56a0ae6f Mon Sep 17 00:00:00 2001 From: r3inbowari Date: Wed, 15 May 2024 18:14:55 +0800 Subject: [PATCH] fix(api): unified packet loss interface --- example/packet_loss/main.go | 4 +++- speedtest/loss.go | 8 ++++---- speedtest/transport/tcp.go | 7 +++++++ 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/example/packet_loss/main.go b/example/packet_loss/main.go index c07ed92..5cf2aaa 100644 --- a/example/packet_loss/main.go +++ b/example/packet_loss/main.go @@ -52,7 +52,9 @@ func main() { // use mixed PacketLoss mixed, err := analyzer.RunMulti(serverList.Hosts()) checkError(err) - fmt.Printf("Mixed packets lossed: %.2f\n", mixed) + fmt.Printf("Mixed packets lossed: %.2f%%\n", mixed.LossPercent()) + fmt.Printf("Mixed packets lossed: %.2f\n", mixed.Loss()) + fmt.Printf("Mixed packets lossed: %s\n", mixed) } func checkError(err error) { diff --git a/speedtest/loss.go b/speedtest/loss.go index dfc4762..719b71a 100644 --- a/speedtest/loss.go +++ b/speedtest/loss.go @@ -61,13 +61,13 @@ func NewPacketLossAnalyzer(options *PacketLossAnalyzerOptions) *PacketLossAnalyz } // RunMulti Mix all servers to get the average packet loss. -func (pla *PacketLossAnalyzer) RunMulti(hosts []string) (float64, error) { +func (pla *PacketLossAnalyzer) RunMulti(hosts []string) (*transport.PLoss, error) { ctx, cancel := context.WithTimeout(context.Background(), pla.options.SamplingDuration) defer cancel() return pla.RunMultiWithContext(ctx, hosts) } -func (pla *PacketLossAnalyzer) RunMultiWithContext(ctx context.Context, hosts []string) (float64, error) { +func (pla *PacketLossAnalyzer) RunMultiWithContext(ctx context.Context, hosts []string) (*transport.PLoss, error) { results := make(map[string]*transport.PLoss) mutex := &sync.Mutex{} wg := &sync.WaitGroup{} @@ -86,7 +86,7 @@ func (pla *PacketLossAnalyzer) RunMultiWithContext(ctx context.Context, hosts [] } wg.Wait() if len(results) == 0 { - return -1, transport.ErrUnsupported + return nil, transport.ErrUnsupported } var pLoss transport.PLoss for _, hostPacketLoss := range results { @@ -94,7 +94,7 @@ func (pla *PacketLossAnalyzer) RunMultiWithContext(ctx context.Context, hosts [] pLoss.Dup += hostPacketLoss.Dup pLoss.Max += hostPacketLoss.Max } - return pLoss.Loss(), nil + return &pLoss, nil } func (pla *PacketLossAnalyzer) Run(host string, callback func(packetLoss *transport.PLoss)) error { diff --git a/speedtest/transport/tcp.go b/speedtest/transport/tcp.go index 87b2236..16219a0 100644 --- a/speedtest/transport/tcp.go +++ b/speedtest/transport/tcp.go @@ -197,6 +197,13 @@ func (p PLoss) Loss() float64 { return 1 - (float64(p.Sent-p.Dup))/float64(p.Max+1) } +func (p PLoss) LossPercent() float64 { + if p.Sent == 0 { + return -1 + } + return p.Loss() * 100 +} + func (client *Client) PacketLoss() (*PLoss, error) { err := client.Write(packetLoss) if err != nil {