当前位置: 首页>>代码示例>>Golang>>正文


Golang net.DialTimeout函数代码示例

本文整理汇总了Golang中net.DialTimeout函数的典型用法代码示例。如果您正苦于以下问题:Golang DialTimeout函数的具体用法?Golang DialTimeout怎么用?Golang DialTimeout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了DialTimeout函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Connect

func (s *Stream) Connect() error {
	var conn io.WriteCloser
	var err error
	path := s.Url.Host + s.Url.Path

	switch {

	case s.Url.Scheme == "tls" || s.Url.Scheme == "ssl":
		tcpConn, dialErr := net.DialTimeout("tcp", path, DIAL_TIMEOUT)
		if dialErr != nil {
			config := &tls.Config{InsecureSkipVerify: s.Conf.AllowSSCert}
			conn = tls.Client(tcpConn, config)
		} else {
			err = dialErr
		}

	case s.Url.Scheme == "file":
		conn, err = os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)

	default:
		conn, err = net.DialTimeout(s.Url.Scheme, path, DIAL_TIMEOUT)

	}
	s.Conn = conn
	return err
}
开发者ID:robinmonjo,项目名称:parklog,代码行数:26,代码来源:parklog.go

示例2: init

func init() {
	t := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: func(n, a string) (net.Conn, error) {
			return net.DialTimeout(n, a, defaultDialTimeout)
		},
	}
	Client = &http.Client{
		Transport: t,
	}
	httpDo = Client

	// copy for InsecureTLS
	tInsecureTLS := http.Transport{
		Proxy: http.ProxyFromEnvironment,
		Dial: func(n, a string) (net.Conn, error) {
			return net.DialTimeout(n, a, defaultDialTimeout)
		},
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	ClientInsecureTLS = &http.Client{
		Transport: &tInsecureTLS,
	}
	httpDoInsecureTLS = ClientInsecureTLS
}
开发者ID:blablacar,项目名称:dgr,代码行数:25,代码来源:http.go

示例3: gatherServer

func (m *Memcached) gatherServer(
	address string,
	unix bool,
	acc plugins.Accumulator,
) error {
	var conn net.Conn
	if unix {
		conn, err := net.DialTimeout("unix", address, defaultTimeout)
		if err != nil {
			return err
		}
		defer conn.Close()
	} else {
		_, _, err := net.SplitHostPort(address)
		if err != nil {
			address = address + ":11211"
		}

		conn, err = net.DialTimeout("tcp", address, defaultTimeout)
		if err != nil {
			return err
		}
		defer conn.Close()
	}

	// Extend connection
	conn.SetDeadline(time.Now().Add(defaultTimeout))

	// Read and write buffer
	rw := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))

	// Send command
	if _, err := fmt.Fprint(rw, "stats\r\n"); err != nil {
		return err
	}
	if err := rw.Flush(); err != nil {
		return err
	}

	values, err := parseResponse(rw.Reader)
	if err != nil {
		return err
	}

	// Add server address as a tag
	tags := map[string]string{"server": address}

	// Process values
	for _, key := range sendMetrics {
		if value, ok := values[key]; ok {
			// Mostly it is the number
			if iValue, errParse := strconv.ParseInt(value, 10, 64); errParse != nil {
				acc.Add(key, value, tags)
			} else {
				acc.Add(key, iValue, tags)
			}
		}
	}
	return nil
}
开发者ID:timjwright,项目名称:telegraf,代码行数:60,代码来源:memcached.go

示例4: rpcConnect

func rpcConnect(addr string) (net.Conn, error) {
	req, err := http.NewRequest("GET", pdRPCPrefix, nil)
	if err != nil {
		return nil, errors.Trace(err)
	}

	urls, err := parseUrls(addr)
	if err != nil {
		return nil, errors.Trace(err)
	}

	for _, url := range urls {
		var conn net.Conn
		switch url.Scheme {
		// used in tests
		case "unix", "unixs":
			conn, err = net.DialTimeout("unix", url.Host, connectPDTimeout)
		default:
			conn, err = net.DialTimeout("tcp", url.Host, connectPDTimeout)
		}

		if err != nil {
			continue
		}
		err = req.Write(conn)
		if err != nil {
			conn.Close()
			continue
		}
		return conn, nil
	}

	return nil, errors.Errorf("connect to %s failed", addr)
}
开发者ID:yangxuanjia,项目名称:tidb,代码行数:34,代码来源:rpc_worker.go

示例5: isNodeNated

func isNodeNated(ip string) bool {
	for {
		_, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", "localhost", DockerHostPort), DialTimeOut*time.Second)
		if err == nil {
			break
		} else {
			time.Sleep(2 * time.Second)
		}
	}

	address := ip
	if address == "" {
		Logger.Printf("Node public IP address return from server is empty, use FQDN instead.")
		address = Conf.CertCommonName
	}
	Logger.Printf("Testing if node %s(%s:%s) is publicly reachable...", Conf.CertCommonName, address, DockerHostPort)
	_, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%s", address, DockerHostPort), DialTimeOut*time.Second)
	if err == nil {
		Logger.Printf("Node %s(%s:%s) is publicly reachable", Conf.CertCommonName, address, DockerHostPort)
		return false
	} else {
		Logger.Printf("Node %s(%s:%s) is not publicly reachable: %s", Conf.CertCommonName, address, DockerHostPort, err)
		return true
	}
}
开发者ID:CloudSide,项目名称:tutum-agent,代码行数:25,代码来源:tunnel.go

示例6: TestAll

func (s *srvLauncherSuite) TestAll() {
	sl := NewServiceLauncher()

	var err error
	var ports = make([]int, 5)

	ports[0], _, err = sl.Start(ZooKeeper)
	s.NoError(err)

	ports[1], _, err = sl.Start(Redis)
	s.NoError(err)

	ports[2], _, err = sl.Start(Etcd)
	s.NoError(err)

	ports[3], _, err = sl.Start(HBase)
	s.NoError(err)

	ports[4], _, err = sl.Start(Gnatsd)
	s.NoError(err)

	for _, port := range ports {
		_, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", port), time.Second)
		s.NoError(err)
	}

	s.NoError(sl.StopAll())

	time.Sleep(5 * time.Second)

	for _, port := range ports {
		_, err := net.DialTimeout("tcp", fmt.Sprintf("localhost:%d", port), time.Second)
		s.Error(err)
	}
}
开发者ID:csigo,项目名称:test,代码行数:35,代码来源:service_launcher_test.go

示例7: newRPCClient

func newRPCClient(addr string) (client *rpcClient, err error) {
	client = &rpcClient{
		addr: addr,
	}

	cmdConn, err := net.DialTimeout("tcp", addr, maxWait)
	if err != nil {
		return nil, err
	}
	client.cmd = rpc.NewClient(cmdConn)

	raftConn, err := net.DialTimeout("tcp", addr, maxWait)
	if err != nil {
		client.raft = client.cmd
	} else {
		client.raft = rpc.NewClient(raftConn)
	}

	prioConn, err := net.DialTimeout("tcp", addr, maxWait)
	if err != nil {
		client.prio = client.raft
	} else {
		client.prio = rpc.NewClient(prioConn)
	}

	msgConn, err := net.DialTimeout("tcp", addr, maxWait)
	if err != nil {
		client.msg = client.cmd
	} else {
		client.msg = rpc.NewClient(msgConn)
	}

	return client, nil
}
开发者ID:jyzhe,项目名称:beehive,代码行数:34,代码来源:rpc.go

示例8: newHTTPClient

func newHTTPClient(u *url.URL, tlsConfig *tls.Config, timeout time.Duration) *http.Client {

	httpTransport := &http.Transport{
		TLSClientConfig: tlsConfig,
	}

	switch u.Scheme {
	default:
		httpTransport.Dial = func(proto, addr string) (net.Conn, error) {
			return net.DialTimeout(proto, addr, timeout)
		}
	case "unix":
		socketPath := u.Path
		unixDial := func(proto, addr string) (net.Conn, error) {
			ret, err := net.DialTimeout("unix", socketPath, timeout)
			return ret, err
		}
		httpTransport.Dial = unixDial
		// Override the main URL object so the HTTP lib won't complain
		u.Scheme = "http"
		u.Host = "unix.sock"
		u.Path = ""
	}
	return &http.Client{Transport: httpTransport}
}
开发者ID:gourao,项目名称:openstorage,代码行数:25,代码来源:client.go

示例9: getconn

// getconn is the unexported function used to connect to Graphite.
// If there is a problem with the connection it retries with an incremental
// sleep time.
// Returns a pointer to the GraphiteServer struct.
func (g *GraphiteServer) getconn() GraphiteServer {
	var (
		err      error
		waitTime time.Duration
	)

	connectAddr := fmt.Sprintf("%s:%d", g.Host, g.Port)

	if g.Timeout == 0 {
		g.Timeout = defaultTimeout * time.Second
	}

	waitTime = initialWaitTime
	g.conn, err = net.DialTimeout("tcp", connectAddr, g.Timeout)
	for err != nil {
		log.Printf(err.Error())
		log.Printf(fmt.Sprintf("error connecting, retrying in %d seconds", waitTime))
		time.Sleep(waitTime * time.Second)

		waitTime += 5
		g.conn, err = net.DialTimeout("tcp", connectAddr, g.Timeout)
	}

	return *g
}
开发者ID:ohlol,项目名称:graphite-go,代码行数:29,代码来源:carbon.go

示例10: gatherServer

func (u *Uwsgi) gatherServer(acc telegraf.Accumulator, url *url.URL) error {
	var err error
	var r io.ReadCloser

	switch url.Scheme {
	case "unix":
		r, err = net.DialTimeout(url.Scheme, url.Path, timeout)
	case "tcp":
		r, err = net.DialTimeout(url.Scheme, url.Host, timeout)
	case "http":
		resp, err := http.Get(url.String())
		if err != nil {
			return fmt.Errorf("Could not connect to uWSGI Stats Server '%s': %s", url.String(), err)
		}
		r = resp.Body
	default:
		return fmt.Errorf("'%s' is not a valid URL", url.String())
	}

	if err != nil {
		return fmt.Errorf("Could not connect to uWSGI Stats Server '%s': %s", url.String(), err)
	}
	defer r.Close()

	var s StatsServer
	s.Url = url.String()

	dec := json.NewDecoder(r)
	dec.Decode(&s)

	u.gatherStatServer(acc, &s)

	return nil
}
开发者ID:miketonks,项目名称:telegraf,代码行数:34,代码来源:uwsgi.go

示例11: processData

func processData(dataCh chan []byte, destinations []Destination) {
	var destConns []net.Conn
	for _, destination := range destinations {
		conn, err := net.DialTimeout("udp", destination.Address, time.Second)
		if err != nil {
			log.Fatalf("ERROR: UDP connection failed - %s", err)
		}
		destConns = append(destConns, conn)
	}

	for data := range dataCh {
		for _, p := range parseMessage(data) {
			for i, destination := range destinations {
				key := destination.Regex.ReplaceAll(p.Key, destination.Replace)
				packet := fmt.Sprintf("%s:%s", key, p.Body)
				conn := destConns[i]
				_, err := conn.Write([]byte(packet))
				if err != nil {
					log.Printf("ERROR: writing to UDP socket - %s", err)
					conn.Close()

					// reconnect
					conn, err := net.DialTimeout("udp", destination.Address, time.Second)
					if err != nil {
						log.Fatalf("ERROR: UDP connection failed - %s", err)
					}
					destConns[i] = conn
				}
			}
		}
	}
}
开发者ID:simplereach,项目名称:statsdtee,代码行数:32,代码来源:main.go

示例12: newHTTPClient

func newHTTPClient(u *url.URL, tlsConfig *tls.Config, timeout time.Duration, setUserTimeout tcpFunc) *http.Client {
	httpTransport := &http.Transport{
		TLSClientConfig: tlsConfig,
	}

	switch u.Scheme {
	default:
		httpTransport.Dial = func(proto, addr string) (net.Conn, error) {
			conn, err := net.DialTimeout(proto, addr, timeout)
			if tcpConn, ok := conn.(*net.TCPConn); ok && setUserTimeout != nil {
				// Sender can break TCP connection if the remote side doesn't
				// acknowledge packets within timeout
				setUserTimeout(tcpConn, timeout)
			}
			return conn, err
		}
	case "unix":
		socketPath := u.Path
		unixDial := func(proto, addr string) (net.Conn, error) {
			return net.DialTimeout("unix", socketPath, timeout)
		}
		httpTransport.Dial = unixDial
		// Override the main URL object so the HTTP lib won't complain
		u.Scheme = "http"
		u.Host = "unix.sock"
		u.Path = ""
	}
	return &http.Client{Transport: httpTransport}
}
开发者ID:swarm-hooks,项目名称:swarm,代码行数:29,代码来源:httpclient.go

示例13: ServeHTTP

func (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	req1, req2 := DuplicateRequest(req)
	go func() {
		defer func() {
			if r := recover(); r != nil && *debug {
				fmt.Println("Recovered in f", r)
			}
		}()
		client_tcp_conn, _ := net.DialTimeout("tcp", h.Alternative, time.Duration(1*time.Second)) // Open new TCP connection to the server
		client_http_conn := httputil.NewClientConn(client_tcp_conn, nil)                          // Start a new HTTP connection on it
		client_http_conn.Write(req1)                                                              // Pass on the request
		client_http_conn.Read(req1)                                                               // Read back the reply
		client_http_conn.Close()                                                                  // Close the connection to the server
	}()
	defer func() {
		if r := recover(); r != nil && *debug {
			fmt.Println("Recovered in f", r)
		}
	}()

	client_tcp_conn, _ := net.DialTimeout("tcp", h.Target, time.Duration(3*time.Second)) // Open new TCP connection to the server
	client_http_conn := httputil.NewClientConn(client_tcp_conn, nil)                     // Start a new HTTP connection on it
	client_http_conn.Write(req2)                                                         // Pass on the request
	resp, _ := client_http_conn.Read(req2)                                               // Read back the reply
	resp.Write(w)                                                                        // Write the reply to the original connection
	client_http_conn.Close()                                                             // Close the connection to the server
}
开发者ID:knifeedge,项目名称:teeproxy,代码行数:27,代码来源:teeproxy.go

示例14: sockConn

func sockConn(timeout time.Duration) (net.Conn, error) {
	daemon := daemonHost()
	daemonURL, err := url.Parse(daemon)
	if err != nil {
		return nil, fmt.Errorf("could not parse url %q: %v", daemon, err)
	}

	var c net.Conn
	switch daemonURL.Scheme {
	case "unix":
		return net.DialTimeout(daemonURL.Scheme, daemonURL.Path, timeout)
	case "tcp":
		if os.Getenv("DOCKER_TLS_VERIFY") != "" {
			// Setup the socket TLS configuration.
			tlsConfig, err := getTLSConfig()
			if err != nil {
				return nil, err
			}
			dialer := &net.Dialer{Timeout: timeout}
			return tls.DialWithDialer(dialer, daemonURL.Scheme, daemonURL.Host, tlsConfig)
		}
		return net.DialTimeout(daemonURL.Scheme, daemonURL.Host, timeout)
	default:
		return c, fmt.Errorf("unknown scheme %v (%s)", daemonURL.Scheme, daemon)
	}
}
开发者ID:fsoppelsa,项目名称:docker,代码行数:26,代码来源:docker_utils.go

示例15: dialRemote

func (conn *ForwardConnection) dialRemote(addr string, lookup_trusted_dns bool) (net.Conn, error) {
	timeout := 10 * time.Second
	//	if !lookup_trusted_dns {
	//		if exist := getDomainCRLFAttr(addr); exist {
	//			conn.try_inject_crlf = true
	//			lookup_trusted_dns = true
	//		}
	//	}
	if lookup_trusted_dns {
		if newaddr, success := lookupAvailableAddress(addr, !conn.prefer_hosts); !success {
			return nil, fmt.Errorf("No available IP found for %s", addr)
		} else {
			log.Printf("Found %s for %s\n", newaddr, addr)
			addr = newaddr
		}
	}
	c, err := net.DialTimeout("tcp", addr, timeout)
	if nil != err && !lookup_trusted_dns {
		if tmp, success := lookupAvailableAddress(addr, !conn.prefer_hosts); success {
			//conn.try_inject_crlf = true
			c, err = net.DialTimeout("tcp", tmp, timeout)
		}
	}
	return c, err
}
开发者ID:juju2013,项目名称:gsnova,代码行数:25,代码来源:forward.go


注:本文中的net.DialTimeout函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。