本文整理汇总了Golang中net.Dial函数的典型用法代码示例。如果您正苦于以下问题:Golang Dial函数的具体用法?Golang Dial怎么用?Golang Dial使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Dial函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: trigger
func (ac *AllCoordinator) trigger(task string, data interface{}) {
/* fmt.Printf("Triggering: %s with %v\n", task, data) */
dataString := getJson(task, data)
// Trying to connect to python
conn, err := net.Dial("unix", ac.devSocket)
for tries := 0; tries < 30 && err != nil; tries++ {
time.Sleep(250 * time.Millisecond)
conn, err = net.Dial("unix", ac.devSocket)
}
// Unsuccessful; die
if err != nil {
log.Fatal("Scheduler is dead.", err)
}
// Sending data
fmt.Fprintf(conn, dataString)
conn.Close()
// Waiting for result
/* buffer := make([]byte, 1024) */
/* size, readerr := conn.Read(buffer) */
/* if readerr != nil { log.Fatal(readerr) } */
// Unserializing and marking as finished
/* result := make(map[string]interface{}) */
/* parseerr := json.Unmarshal(buffer[:size], &result) */
/* if parseerr != nil { log.Fatal(parseerr) } */
}
示例2: connect
func (p *Proxy) connect(req *http.Request) (*http.Response, net.Conn, error) {
if p.proxyURL != nil {
log.Debugf("martian: CONNECT with downstream proxy: %s", p.proxyURL.Host)
conn, err := net.Dial("tcp", p.proxyURL.Host)
if err != nil {
return nil, nil, err
}
pbw := bufio.NewWriter(conn)
pbr := bufio.NewReader(conn)
req.Write(pbw)
pbw.Flush()
res, err := http.ReadResponse(pbr, req)
if err != nil {
return nil, nil, err
}
return res, conn, nil
}
log.Debugf("martian: CONNECT to host directly: %s", req.URL.Host)
conn, err := net.Dial("tcp", req.URL.Host)
if err != nil {
return nil, nil, err
}
return proxyutil.NewResponse(200, nil, req), conn, nil
}
示例3: doTestMsgpackRpcSpecGoClientToPythonSvc
func doTestMsgpackRpcSpecGoClientToPythonSvc(t *testing.T) {
if testSkipRPCTests {
return
}
// openPorts are between 6700 and 6800
r := rand.New(rand.NewSource(time.Now().UnixNano()))
openPort := strconv.FormatInt(6700+r.Int63n(99), 10)
// openPort := "6792"
cmd := exec.Command("python", "test.py", "rpc-server", openPort, "4")
checkErrT(t, cmd.Start())
bs, err2 := net.Dial("tcp", ":"+openPort)
for i := 0; i < 10 && err2 != nil; i++ {
time.Sleep(50 * time.Millisecond) // time for python rpc server to start
bs, err2 = net.Dial("tcp", ":"+openPort)
}
checkErrT(t, err2)
cc := MsgpackSpecRpc.ClientCodec(bs, testMsgpackH)
cl := rpc.NewClientWithCodec(cc)
defer cl.Close()
var rstr string
checkErrT(t, cl.Call("EchoStruct", TestRpcABC{"Aa", "Bb", "Cc"}, &rstr))
//checkEqualT(t, rstr, "{'A': 'Aa', 'B': 'Bb', 'C': 'Cc'}")
var mArgs MsgpackSpecRpcMultiArgs = []interface{}{"A1", "B2", "C3"}
checkErrT(t, cl.Call("Echo123", mArgs, &rstr))
checkEqualT(t, rstr, "1:A1 2:B2 3:C3", "rstr=")
cmd.Process.Kill()
}
示例4: sendConnection
/*
* send connections to nodes with greater Names
* and stores connections into connections map
* @param latterNodes
* map that contains all nodes with greater or equal Node names
*
* @param LocalNode
**/
func sendConnection(latterNodes map[string]Node) {
defer wg.Done()
for _, node := range latterNodes {
conn, err := net.Dial("tcp", node.IP+":"+strconv.Itoa(node.Port))
for err != nil {
fmt.Print(".")
time.Sleep(time.Second * 1)
conn, err = net.Dial("tcp", node.IP+":"+strconv.Itoa(node.Port))
}
if node.Name == LocalNode.Name {
localConn = conn
localEncoder = gob.NewEncoder(conn)
} else {
addConnection(node.Name, conn)
}
/* send an initial ping message to other side of the connection */
timestampMutex.Lock()
msg := Message{LocalNode.Name, node.Name, "ping", "ping", 0, vectorTimeStamp}
timestampMutex.Unlock()
encoder := gob.NewEncoder(conn)
encoder.Encode(msg)
}
fmt.Println()
}
示例5: TestServerRunAndStop
func TestServerRunAndStop(t *testing.T) {
fmt.Println("TestServerRunAndStop")
// var test_port = "60000"
// var test_address = "127.0.0.1:" + test_port
srv := NewServer(test_port, "", "", 1024, false, false, 2, 1024)
srv.RunServer()
defer srv.StopServer() // if test will be broken down before server will be closed.
time.Sleep(time.Millisecond * time.Duration(10)) // Let's wait a bit while goroutines will start
connection, err := net.Dial("tcp", test_address)
if err != nil {
t.Fatalf("Server wasn't run: %s", err)
}
var test_msg = []byte("Test1\r\n")
_, err = connection.Write(test_msg)
if err != nil {
t.Fatalf("Stream is unavailable to transmit data: ", err)
}
var response = make([]byte, 255)
fmt.Println("Trying to read response...")
_, err = connection.Read(response[0:])
if err != nil {
t.Fatalf("Stream is unavailable to transmit data: ", err)
}
if len(response) == 0 {
t.Fatalf("Server doesn't response.")
}
fmt.Println("Response: ", string(response))
srv.StopServer()
connection.Close()
connection, err = net.Dial("tcp", test_address)
if err == nil {
t.Fatalf("Server is still running at %s", test_address)
}
}
示例6: dial
// dial is based on log/syslog.Dial().
// It was copied out as log/syslog.Dial() doesn't properly use the basename of ARGV[0].
func (sw *SyslogHandler) dial() error {
if sw.syslogProtocol == "" || sw.syslogProtocol == "unix" {
logTypes := []string{"unixgram", "unix"}
var logPaths []string
if sw.syslogAddr != "" {
logPaths = []string{sw.syslogAddr}
} else {
logPaths = []string{"/dev/log", "/var/run/syslog", "/var/run/log"}
}
for _, network := range logTypes {
for _, path := range logPaths {
conn, err := net.Dial(network, path)
if err != nil {
continue
}
sw.syslogConnection = conn
return nil
}
}
return fmt.Errorf("Could not find listening syslog daemon")
}
connection, err := net.Dial(sw.syslogProtocol, sw.syslogAddr)
if err != nil {
return err
}
sw.syslogConnection = connection
return nil
}
示例7: SetupConnections
func (lights *Lights) SetupConnections() error {
lights.connections = make(map[string]*net.Conn)
// Don't enable lights for a side if the controller address is not configured.
if len(eventSettings.RedGoalLightsAddress) != 0 {
conn, err := net.Dial("udp4", eventSettings.RedGoalLightsAddress)
lights.connections["red"] = &conn
if err != nil {
return err
}
} else {
lights.connections["red"] = nil
}
if len(eventSettings.BlueGoalLightsAddress) != 0 {
conn, err := net.Dial("udp4", eventSettings.BlueGoalLightsAddress)
lights.connections["blue"] = &conn
if err != nil {
return err
}
} else {
lights.connections["blue"] = nil
}
lights.newConnections = true
return nil
}
示例8: autoDial
// Automatically chooses between unix sockets and tcp sockets for
// dialing.
func autoDial(place string) (net.Conn, error) {
if strings.Contains(place, "/") {
return net.Dial("unix", place)
}
return net.Dial("tcp", place)
}
示例9: dial
func dial(host string) (conn *http.ClientConn) {
var tcp net.Conn
var err os.Error
fmt.Fprintf(os.Stderr, "http-gonsole: establishing a TCP connection ...\n")
proxy := os.Getenv("HTTP_PROXY")
if len(proxy) > 0 {
proxy_url, _ := http.ParseURL(proxy)
tcp, err = net.Dial("tcp", proxy_url.Host)
} else {
tcp, err = net.Dial("tcp", host)
}
if err != nil {
fmt.Fprintln(os.Stderr, "http-gonsole:", err)
os.Exit(1)
}
if *useSSL {
cf := &tls.Config{Rand: rand.Reader, Time: time.Nanoseconds}
ssl := tls.Client(tcp, cf)
conn = http.NewClientConn(ssl, nil)
if len(proxy) > 0 {
tcp.Write([]byte("CONNECT " + host + " HTTP/1.0\r\n\r\n"))
b := make([]byte, 1024)
tcp.Read(b)
}
} else {
conn = http.NewClientConn(tcp, nil)
}
return
}
示例10: dial
func (l *Local) dial(addr proxy.Addr) (conn net.Conn, isTunnel bool, err error) {
host := string(addr.Host)
l.log.Info(log.M{"addr_type": addr.Type, "host": host, "port": addr.Port})
if host := string(addr.Host); l.isDirectConnect(host) {
conn, err = net.Dial("tcp", addr.String())
if err == nil {
if l.log.IsDebugEnable() {
l.log.Debug(log.M{"connect_mode": "direct", "host": host})
}
return conn, false, nil
}
l.log.Error(log.M{"msg": "direct connect failed, try tunnel.", "host": host, "err": err.Error()})
}
// tunnel
tunnel := l.randTunnel()
conn, err = net.Dial("tcp", tunnel.Addr())
if err == nil {
conn, err = tunnel.Client(conn, addr)
if err != nil {
l.log.Error(log.M{"msg": "tunnel handshake failed", "addr": tunnel.Addr(), "err": err.Error()})
}
} else {
l.log.Error(log.M{"msg": "connect tunnel server failed", "addr": tunnel.Addr(), "err": err.Error()})
}
return conn, true, err
}
示例11: Dial
// Dial generates a private/public key pair,
// connects to the server, perform the handshake
// and return a reader/writer.
func Dial(addr string) (io.ReadWriteCloser, error) {
pub, priv, err := box.GenerateKey(rand.Reader)
// fmt.Printf("priv is %v\n", priv)
fmt.Printf("pub is %v\n", pub)
if err != nil {
panic(err)
}
conn, err := net.Dial("tcp", addr)
if err != nil {
panic(err)
}
header := &[64]byte{'p', 'r', 'i', 'v', 'p', 'u', 'b'}
buf := make([]byte, 96)
copy(buf[:64], header[:64])
copy(buf[64:], pub[0:32])
fmt.Printf("what is the end%v\n", pub[32:])
fmt.Printf("combination %v\n", buf)
conn2, err := net.Dial("tcp", addr)
if err != nil {
panic(err)
}
conn2.Write(buf)
conn2.Close()
var rwc secureConnection
secureR := NewSecureReader(conn, priv, pub)
secureW := NewSecureWriter(conn, priv, pub)
rwc = secureConnection{secureW, secureR}
return rwc, err
}
示例12: dialAny
//
// Dial a socket using tcp://host:port, tls://host:port, or unix://path
//
func dialAny(uri string, tls_config tls.Config) (net.Conn, error) {
if len(uri) < 7 {
err_str := "uri too short"
log.WithFields(log.Fields{
"error": err_str,
}).Error("cannot dial")
return nil, errors.New(err_str)
}
if uri[:6] == "tls://" {
address := uri[6:]
return tls.Dial("tcp", address, &tls_config)
} else if uri[:6] == "tcp://" {
address := uri[6:]
return net.Dial("tcp", address)
} else if uri[:7] == "unix://" {
address := uri[7:]
return net.Dial("unix", address)
}
err_str := "unrecognized protocol"
log.WithFields(log.Fields{
"error": err_str,
"uri": uri,
}).Error("cannot dial")
return nil, errors.New(err_str)
}
示例13: connectRoutine
func (c *TcpConnector) connectRoutine() {
c.waitor.Add(1)
defer c.waitor.Done()
service := c.sc.Ip + ":" + strconv.Itoa(int(c.sc.Port))
conn, err := net.Dial("tcp", service)
if err == nil {
c.connChan <- conn
return
}
for {
select {
case <-time.After(ReconnectInterval):
if c.quit {
return
}
conn, err := net.Dial("tcp", service)
if err == nil {
if c.quit {
conn.Close()
return
}
c.connChan <- conn
return
}
}
}
}
示例14: TestRunStop
func TestRunStop(t *testing.T) {
server := NewServer(5555, 6666)
go server.ListenAndServe()
time.Sleep(500 * time.Millisecond)
conn, err := net.Dial("tcp", ":5555")
if err != nil {
t.Error("Failed to connect to push server client port.")
}
defer conn.Close()
conn1, err := net.Dial("tcp", ":6666")
if err != nil {
t.Error("Failed to connect to push server control port.")
}
defer conn1.Close()
server.close()
time.Sleep(500 * time.Millisecond)
conn2, err := net.Dial("tcp", ":5555")
if err == nil {
t.Error("Expecting closed server but still connected successfully.")
defer conn2.Close()
}
conn3, err := net.Dial("tcp", ":6666")
if err == nil {
t.Error("Expecting closed server but still connected to control port successfully.")
defer conn3.Close()
}
}
示例15: GetTestResult
func GetTestResult() (s string) {
const ERR = "protocol not available"
_, err := net.Dial("tcp", "127.0.0.1:80")
if err != nil && strings.Contains(err.Error(), ERR) {
s += "MISSING TCP: " + err.Error() + "\n\n"
} else {
s += "GOT TCP! " + err.Error() + "\n\n"
}
_, err = net.Dial("tcp4", "127.0.0.1:80")
if err != nil && strings.Contains(err.Error(), ERR) {
s += "MISSING TCP4: " + err.Error() + "\n\n"
} else {
s += "GOT TCP4! " + err.Error() + "\n\n"
}
_, err = net.Dial("tcp6", "127.0.0.1:80")
if err != nil && strings.Contains(err.Error(), ERR) {
s += "MISSING TCP6: " + err.Error() + "\n\n"
} else {
s += "GOT TCP6! " + err.Error() + "\n\n"
}
_, err = net.Dial("udp", "127.0.0.1:80")
if err != nil && strings.Contains(err.Error(), ERR) {
s += "MISSING UDP: " + err.Error() + "\n\n"
} else {
s += "GOT UDP! " + err.Error() + "\n\n"
}
return
}