コード例 #1
0
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
0
ファイル: proxy.go プロジェクト: rlugojr/martian
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
0
ファイル: codec_test.go プロジェクト: CNDonny/scope
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
0
ファイル: MessagePasser.go プロジェクト: arminm/multegula
/*
 * 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
0
ファイル: server_test.go プロジェクト: UIKit0/memorango
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
0
ファイル: syslog.go プロジェクト: christianbak/sawmill
// 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
0
ファイル: lights.go プロジェクト: fangeugene/cheesy-arena
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
0
ファイル: dog.go プロジェクト: uhoh-itsmaciek/dog
// 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
0
ファイル: http-gonsole.go プロジェクト: aht/http-gonsole
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
0
ファイル: local.go プロジェクト: cosiner/tunnel
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
0
ファイル: main.go プロジェクト: tkschmidt/golangChallenge2
// 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
0
ファイル: network.go プロジェクト: hkparker/proxyd
//
// 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
0
ファイル: tcp_connector.go プロジェクト: zwczou/goserver
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
0
ファイル: taiji_test.go プロジェクト: rlei/taiji
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
0
ファイル: gosocket.go プロジェクト: diegomontoya/gosocket
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

}
コード例 #16
0
func single_stew_echo_client() {
	ctx := make_sc_ctx()
	sc1, err := net.Dial("tcp", "127.0.0.1:20999")
	if err != nil {
		panic(err.Error())
	}

	go ctx.AttachSC(sc1, false)
	sc2, err := net.Dial("tcp", "127.0.0.1:20999")
	if err != nil {
		panic(err.Error())
	}
	go ctx.AttachSC(sc2, false)
	kilog.Info("Two wires attached!")
	kilog.Info("Sending hello world...")
	ctx.write_ch <- sc_message{0x01, []byte(" ")}
	close(<-ctx.close_ch_ch)
	ctx.write_ch <- sc_message{0x00, []byte("hello")}
	sc3, err := net.Dial("tcp", "127.0.0.1:20999")
	if err != nil {
		panic(err.Error())
	}
	go ctx.AttachSC(sc3, false)
	ctx.write_ch <- sc_message{0x02, []byte("world")}
	close(<-ctx.close_ch_ch)
	fmt.Print(string((<-ctx.ordered_ch).payload))
	fmt.Print(string((<-ctx.ordered_ch).payload))
	fmt.Println(string((<-ctx.ordered_ch).payload))
}
コード例 #17
0
ファイル: whitelist_test.go プロジェクト: jamesbjackson/cfssl
func TestNetConn(t *testing.T) {
	wl := NewBasic()
	defer close(shutdown)

	go setupTestServer(t, wl)
	<-proceed

	conn, err := net.Dial("tcp", "127.0.0.1:4141")
	if err != nil {
		t.Fatalf("%v", err)
	}
	body, err := ioutil.ReadAll(conn)
	if err != nil {
		t.Fatalf("%v", err)
	}
	if string(body) != "NO" {
		t.Fatalf("Expected NO, but received %s", body)
	}
	conn.Close()

	addIPString(wl, "127.0.0.1", t)
	conn, err = net.Dial("tcp", "127.0.0.1:4141")
	if err != nil {
		t.Fatalf("%v", err)
	}
	body, err = ioutil.ReadAll(conn)
	if err != nil {
		t.Fatalf("%v", err)
	}
	if string(body) != "OK" {
		t.Fatalf("Expected OK, but received %s", body)
	}
	conn.Close()

}
コード例 #18
0
ファイル: client.go プロジェクト: heidi-ann/ios
func connect(addrs []string, tries int, hint int) (net.Conn, int, error) {
	var conn net.Conn
	var err error

	// first, try on to connect to the most likely leader
	glog.Info("Trying to connect to ", addrs[hint])
	conn, err = net.Dial("tcp", addrs[hint])
	// if successful
	if err == nil {
		glog.Infof("Connect established to %s", addrs[hint])
		return conn, hint, err
	}
	//if unsuccessful
	glog.Warning(err)

	// if fails, try everyone else
	for i := range addrs {
		for t := tries; t > 0; t-- {
			glog.Info("Trying to connect to ", addrs[i])
			conn, err = net.Dial("tcp", addrs[i])

			// if successful
			if err == nil {
				glog.Infof("Connect established to %s", addrs[i])
				return conn, i, err
			}

			//if unsuccessful
			glog.Warning(err)
		}
	}

	return conn, hint + 1, err
}
コード例 #19
0
ファイル: proxier_test.go プロジェクト: htomika/kubernetes
func TestProxyStop(t *testing.T) {
	port, err := echoServer(t, "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}

	lb := NewLoadBalancerRR()
	lb.OnUpdate([]api.Endpoints{{JSONBase: api.JSONBase{ID: "echo"}, Endpoints: []string{net.JoinHostPort("127.0.0.1", port)}}})

	p := NewProxier(lb)

	proxyPort, err := p.addServiceOnUnusedPort("echo")
	if err != nil {
		t.Fatalf("error adding new service: %#v", err)
	}
	conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", proxyPort))
	if err != nil {
		t.Fatalf("error connecting to proxy: %v", err)
	}
	conn.Close()

	p.StopProxy("echo")
	// Wait for the port to really close.
	time.Sleep(2 * time.Second)
	_, err = net.Dial("tcp", net.JoinHostPort("127.0.0.1", proxyPort))
	if err == nil {
		t.Fatalf("Unexpected non-error.")
	}
}
コード例 #20
0
ファイル: http.go プロジェクト: ducktsmt/snova-gae
func HttpTunnelDial(network, addr string, tunnel_url *url.URL) (c net.Conn, err error) {
	if nil == tunnel_url {
		return net.Dial(network, addr)
	}
	c, err = net.Dial("tcp", tunnel_url.Host)
	if nil != err {
		return
	}
	reader := bufio.NewReader(c)
	req := &http.Request{
		Method: "CONNECT",
		URL:    &url.URL{Host: addr},
		Host:   addr,
		Header: make(http.Header),
	}
	err = req.Write(c)
	if nil != err {
		return
	}
	var res *http.Response
	res, err = http.ReadResponse(reader, req)
	if nil != err {
		return
	}
	if res.StatusCode >= 300 {
		c.Close()
		return nil, errors.New(res.Status)
	}
	return
}
コード例 #21
0
ファイル: retry_test.go プロジェクト: uber/tchannel-go
func TestRetryNetConnect(t *testing.T) {
	e := getTestErrors()
	ch := testutils.NewClient(t, nil)
	defer ch.Close()

	ctx, cancel := NewContext(time.Second)
	defer cancel()

	closedAddr := testutils.GetClosedHostPort(t)
	listenC, err := net.Listen("tcp", ":0")
	require.NoError(t, err, "Listen failed")
	defer listenC.Close()

	counter := 0
	f := func(ctx context.Context, rs *RequestState) error {
		counter++
		if !rs.HasRetries(e.Connection) {
			c, err := net.Dial("tcp", listenC.Addr().String())
			if err == nil {
				c.Close()
			}
			return err
		}

		_, err := net.Dial("tcp", closedAddr)
		return err
	}

	assert.NoError(t, ch.RunWithRetry(ctx, f), "RunWithRetry should succeed")
	assert.Equal(t, 5, counter, "RunWithRetry should have run f 5 times")
}
コード例 #22
0
ファイル: proxy.go プロジェクト: clarelin/asuran
func (p *Proxy) parseDomainAsDial(target, client string) func(network, addr string) (gonet.Conn, error) {
	if p.domainOp == nil {
		return nil
	}

	u, err := url.Parse(target)
	if err != nil {
		return nil
	}

	domain, port, err := gonet.SplitHostPort(u.Host)
	if err != nil {
		domain = u.Host
	}

	if len(port) == 0 {
		port = "80"
	}

	a := p.domainOp.Action(client, domain)
	if a == nil || len(a.IP) == 0 {
		return nil
	}

	address := gonet.JoinHostPort(a.IP, port)
	return func(network, addr string) (gonet.Conn, error) {
		if network == "tcp" {
			return gonet.Dial(network, address)
		} else {
			return gonet.Dial(network, addr)
		}
	}
}
コード例 #23
0
ファイル: client.go プロジェクト: rovaughn/rendezvous
func Dial(rendezvousAddr, key string) (net.Conn, error) {
	rendezvousConn, err := net.Dial("tcp", rendezvousAddr)
	if err != nil {
		return nil, err
	}
	defer rendezvousConn.Close()

	decoder := json.NewDecoder(rendezvousConn)
	encoder := json.NewEncoder(rendezvousConn)

	message := map[string]string{
		"action": "dial",
		"key":    key,
	}

	if err := encoder.Encode(message); err != nil {
		return nil, err
	}

	var addr string

	if err := decoder.Decode(&addr); err != nil {
		return nil, err
	}

	return net.Dial("tcp", addr)
}
コード例 #24
0
func TestCarbonHandleConnection(t *testing.T) {
	log.Info("START TestCarbonHandleConnection")
	defer log.Info("END   TestCarbonHandleConnection")
	listenFrom := &config.ListenFrom{
		ListenAddr: workarounds.GolangDoesnotAllowPointerToStringLiteral("localhost:0"),
	}

	ctx := context.Background()
	forwardTo := dptest.NewBasicSink()
	listener, err := ListenerLoader(ctx, forwardTo, listenFrom)
	defer listener.Close()

	listeningDialAddress := fmt.Sprintf("localhost:%d", nettest.TCPPort(listener.psocket))

	conn, err := net.Dial("tcp", listeningDialAddress)
	assert.NoError(t, err)
	conn.Close()
	assert.Error(t, listener.handleConnection(conn))

	conn, err = net.Dial("tcp", listeningDialAddress)
	assert.NoError(t, err)
	waitChan := make(chan struct{})
	go func() {
		time.Sleep(time.Millisecond * 10)
		assert.NoError(t, conn.Close())
		close(waitChan)
	}()
	<-waitChan

	for atomic.LoadInt64(&listener.stats.totalEOFCloses) == 0 {
		time.Sleep(time.Millisecond)
	}
}
コード例 #25
0
ファイル: connhandler.go プロジェクト: jpanda109/gocc
// Dial connects to server at address
func (handler *ConnHandler) Dial(addr string) ([]Peer, error) {
	var peers []Peer
	conn, err := net.Dial("tcp", addr)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	writer := bufio.NewWriter(conn)
	reader := bufio.NewReader(conn)
	line, _ := reader.ReadString('\n')
	line = strings.Trim(line, "\n")
	addrs := strings.Split(line, ";")
	info := strings.Split(addrs[0], ",")
	writer.WriteString(handler.String() + "\n")
	writer.Flush()
	peers = append(peers, NewPeer(conn, conn, info[0], info[1]))
	for _, a := range addrs[1:] {
		info := strings.Split(a, ",")
		c, _ := net.Dial("tcp", info[0])
		writer = bufio.NewWriter(c)
		writer.WriteString(handler.String() + "\n")
		writer.Flush()
		reader = bufio.NewReader(c)
		line, _ = reader.ReadString('\n')
		peers = append(peers, NewPeer(c, c, info[0], info[1]))
	}
	return peers, nil
}
コード例 #26
0
ファイル: main.go プロジェクト: fliar/tcpmatch
func clientMain() {
	conn, err := net.Dial(PROTOCOL, SERVER_ADDR)
	if err != nil {
		panic(err.Error())
	}
	fmt.Println("Connected to ", conn.RemoteAddr().String())
	fmt.Println("I'm connecting on ", conn.LocalAddr().String())
	reader := bufio.NewReader(conn)
	portStr, _ := reader.ReadString(DELIM)
	portStr = strings.TrimRight(portStr, string(DELIM))
	fmt.Println("Getting:", portStr)
	//connect to NAT port
	connNAT, err := net.Dial(PROTOCOL, SERVER_IP+portStr)
	if err != nil {
		panic(err.Error())
	}
	fmt.Println("NAT Connected to ", connNAT.RemoteAddr().String())
	fmt.Println("NAT I'm connecting on ", connNAT.LocalAddr().String())
	fmt.Println("NAT Network ", connNAT.LocalAddr().Network())

	natAddr := connNAT.LocalAddr().String()
	connNAT.Close()
	ln, err := net.Listen(PROTOCOL, natAddr)
	if err != nil {
		panic(err.Error())
	}
	fmt.Println("NAT listening on ", natAddr)
	connNAT, err = ln.Accept()
	if err != nil {
		panic(err.Error())
	}
	fmt.Println("NAT", connNAT.LocalAddr().String(), "connected")
}
コード例 #27
0
ファイル: main.go プロジェクト: dickeyxxx/golang-dns-windows
func main() {
	fmt.Println("starting")

	fmt.Println("google.com:80")
	_, err := net.Dial("tcp", "google.com:80")
	printerr(err)

	fmt.Println("github.com:443")
	_, err = net.Dial("tcp", "github.com:443")
	printerr(err)

	fmt.Println("http://github.com")
	_, err = goreq.Request{Uri: "http://www.github.com"}.Do()
	printerr(err)

	fmt.Println("https://github.com")
	_, err = goreq.Request{Uri: "https://www.github.com"}.Do()
	printerr(err)

	fmt.Println("http://google.com")
	_, err = goreq.Request{Uri: "http://www.google.com"}.Do()
	printerr(err)

	fmt.Println("https://google.com")
	_, err = goreq.Request{Uri: "https://www.google.com"}.Do()
	printerr(err)

	fmt.Println("done")
}
コード例 #28
0
ファイル: kt_base_test.go プロジェクト: wheelcomplex/golibs
func startServer(t testing.TB) *exec.Cmd {
	port := strconv.Itoa(KTPORT)

	if _, err := net.Dial("tcp", KTHOST+":"+port); err == nil {
		t.Fatal("Not expecting ktserver to exist yet. Perhaps: killall ktserver?")
	}

	cmd := exec.Command("ktserver", "-host", KTHOST, "-port", port, "%")

	if err := cmd.Start(); err != nil {
		t.Fatal("failed to start KT: ", err)
	}

	for i := 0; ; i++ {
		conn, err := net.Dial("tcp", KTHOST+":"+port)
		if err == nil {
			conn.Close()
			return cmd
		}
		time.Sleep(50 * time.Millisecond)
		if i > 50 {
			t.Fatal("failed to start KT: ", err)
		}
	}
}
コード例 #29
0
// Test that MaxTCPConections is respected when max==1
func TestConcurrentConns1(t *testing.T) {
	listener := TcpListener{
		ServiceAddress:         ":8196",
		AllowedPendingMessages: 10000,
		MaxTCPConnections:      1,
	}
	listener.parser, _ = parsers.NewInfluxParser()

	acc := &testutil.Accumulator{}
	require.NoError(t, listener.Start(acc))
	defer listener.Stop()

	time.Sleep(time.Millisecond * 25)
	_, err := net.Dial("tcp", "127.0.0.1:8196")
	assert.NoError(t, err)

	// Connection over the limit:
	conn, err := net.Dial("tcp", "127.0.0.1:8196")
	assert.NoError(t, err)
	net.Dial("tcp", "127.0.0.1:8196")
	buf := make([]byte, 1500)
	n, err := conn.Read(buf)
	assert.NoError(t, err)
	assert.Equal(t,
		"Telegraf maximum concurrent TCP connections (1) reached, closing.\n"+
			"You may want to increase max_tcp_connections in"+
			" the Telegraf tcp listener configuration.\n",
		string(buf[:n]))

	_, err = conn.Write([]byte(testMsg))
	assert.NoError(t, err)
	time.Sleep(time.Millisecond * 10)
	assert.Zero(t, acc.NFields())
}
コード例 #30
0
// Test syntax of write command
func TestSyntax(t *testing.T) {
	name := "hi.txt"
	contents := "bye"
	exptime := 300000
	conn, err := net.Dial("tcp", "localhost:8080")
	if err != nil {
		t.Error(err.Error()) // report error through testing framework
	}
	scanner := bufio.NewScanner(conn)
	// Write a file
	fmt.Fprintf(conn, "write ab %v %v\r\n%v\r\n", name, exptime, contents)
	scanner.Scan()                  // read first line
	resp := scanner.Text()          // extract the text from the buffer
	arr := strings.Split(resp, " ") // split into OK and <version>
	expect(t, arr[0], "ERR_CMD_ERR")
	conn, err = net.Dial("tcp", "localhost:8080")
	if err != nil {
		t.Error(err.Error()) // report error through testing frame
	}
	scanner = bufio.NewScanner(conn)
	fmt.Fprintf(conn, "read %v\r\n", name) // try a read now
	scanner.Scan()
	arr = strings.Split(scanner.Text(), " ")
	expect(t, arr[0], "CONTENTS")
	scanner.Scan()
	expect(t, contents, scanner.Text())

}