golang - 为什么net.DialTimeout会在一半的时间内超时?

时间:2016-05-18 08:24:03

标签: go

这是我的测试代码,我设置6s超时,但程序只执行3s,为什么?

package main

import "net"
import "time"
import "fmt"

func main() {
    fmt.Println(time.Now())
    conn, err := net.DialTimeout("tcp", "google.com:80",6*time.Second) // chinese people can't access google
    fmt.Println(time.Now())
    fmt.Println(conn,err)
}

测试结果:

2016-05-18 16:21:31.325340213 +0800 CST
2016-05-18 16:21:34.32909193 +0800 CST
<nil> dial tcp 59.24.3.173:80: i/o timeout

1 个答案:

答案 0 :(得分:0)

您的代码没问题,您的网络/互联网连接/互联网路线存在问题 例如,如果你和谷歌之间的路由器/设备超载(或任何问题...)它可能每隔几秒就会丢弃一些数据包,我的猜测。

我的测试结果:

10 1.0000572s 0 <nil> dial tcp: i/o timeout
9 1.0000572s 3 <nil> dial tcp: i/o timeout
8 1.0000572s 3 <nil> dial tcp: i/o timeout
7 1.0000572s 3 <nil> dial tcp: i/o timeout
6 1.0000572s 4 <nil> dial tcp: i/o timeout
5 1.0000572s 4 <nil> dial tcp: i/o timeout
4 1.0000572s 4 <nil> dial tcp: i/o timeout
3 1.0000572s 4 <nil> dial tcp: i/o timeout
2 1.0000572s 4 <nil> dial tcp: i/o timeout
1 1.0000572s 4 <nil> dial tcp: i/o timeout

然后我禁用了网络连接:

package main

import (
    "fmt"
    "net"
    "time"
)

type res struct {
    d time.Duration
    t int64
    n net.Conn
    e error
}

func check(c chan res) {
    t := time.Now()
    conn, err := net.DialTimeout("tcp", "google.com:80", 1*time.Second)
    d := time.Now().Sub(t)
    c <- res{d, (t.UnixNano() - t0) / time.Millisecond.Nanoseconds(), conn, err}
}

var t0 int64 = time.Now().UnixNano()

func main() {
    numberOfJobs := 10
    c := make(chan res, numberOfJobs)
    for i := 0; i < numberOfJobs; i++ {
        go check(c)
    }
    for r := range c {
        fmt.Println(numberOfJobs, r.d, r.t, r.n, r.e)
        numberOfJobs--
        if numberOfJobs == 0 {
            break
        }
    }
}

带有10个并发测试的测试样本代码:

namespace app {
    'use strict';

    export interface IMyScope {
        // ngModel: Date;
        testing: string;
    }

    class DateTime implements angular.IDirective {
        public restrict: string = 'E';
        public template: string = '<div>Input: {{testing | json}}</div>';
        public scope: any = {
            testing: '='
        };

        // @ngInject
        controller: any = ($scope: IMyScope): void => {
            console.log($scope.testing);
        };

        link: any = (scope: IMyScope , 
                    element: angular.IAugmentedJQuery, 
                    attrs: angular.IAttributes, 
                    ctrl: any): void => {
            console.log(scope.testing);
        }
    }


    angular
        .module('app')
        .directive('dateTime', [() => new DateTime()]);
}