2016-05-18 4 views
3

これは私のテストコードですが、私は6秒のタイムアウトを設定しましたが、プログラムは3秒間だけ実行します、なぜですか?golang - なぜnet.DialTimeoutは時間の半分をタイムアウトにするのですか?

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) 
} 

テストの結果:あなたのコードはOKです

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 
+0

ゴーバージョンgo1.6.2でlinux/amd64 – rox

+0

はここでもうまくいきます。 '2016-05-18 16:34:55.364568407 +0800 CST 2016-05-18 16:35:01.365609996 +0800 CST ダイヤルtcp:i/oタイムアウト' –

+1

見てください:https://github.com/ golang/go/blob/495e3c60aa61615dd603050ac47f86468f8222b6/src/net/dial.go#L18 – molivier

答えて

0

、インターネットへのネットワーク/インターネット接続/ルートに問題があります。
たとえば、あなたとGoogleの間のルータ/デバイス(または何らかの問題)が数秒ごとにいくつかのパケットをドロップする可能性があります。

私のテスト結果:

10 192.0109ms 3 &{{0xc082082900}} <nil> 
9 192.0109ms 3 &{{0xc082082780}} <nil> 
8 192.0109ms 3 &{{0xc082082000}} <nil> 
7 197.0112ms 3 &{{0xc082015c80}} <nil> 
6 227.0129ms 3 &{{0xc082082300}} <nil> 
5 372.0212ms 3 &{{0xc082082180}} <nil> 
4 375.0214ms 0 &{{0xc082015e00}} <nil> 
3 375.0214ms 3 &{{0xc082082600}} <nil> 
2 375.0214ms 3 &{{0xc082082480}} <nil> 
1 378.0216ms 3 &{{0xc082082a80}} <nil> 

その後、I無効なネットワーク接続:

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 

10の同時テストとテストサンプルコード:

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 
     } 
    } 
} 
関連する問題