コード例 #1
0
ファイル: myclienttest.go プロジェクト: cjlibra/serialxiu
func ping(num int, count *int) int {
	tcpAddr, _ := net.ResolveTCPAddr("tcp4", "localhost:8080")
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	howmuch := 0
	for err != nil {
		time.Sleep(1 * time.Second)
		conn, err = net.DialTCP("tcp", nil, tcpAddr)
		if err == nil {
			break
		} else {
			howmuch += 1
		}

		if howmuch == 50 {
			ioutil.WriteFile("log.txt", []byte("i can not dial 50 "), 0644)
			fmt.Println("i can not dial after 50times")
			return -1
		}
	}
	*count += 1
	fmt.Println("i am ", num)
	for {
		_, _ = conn.Write([]byte("Ping"))
		var buff [4]byte
		_, _ = conn.Read(buff[0:])
		time.Sleep(5 * time.Second)
	}

	conn.Close()
	return 0
}
コード例 #2
0
/**
 * Create connection to server using unix socket or tcp/ip then setup buffered reader/writer
 */
func (handlerSocket *HandlerSocket) connect() (err error) {
	localAddress, _ := net.ResolveTCPAddr("tcp", "0.0.0.0:0")
	targetAddress := fmt.Sprintf("%s:%d", handlerSocket.auth.host, handlerSocket.auth.readPort)
	wrTargetAddress := fmt.Sprintf("%s:%d", handlerSocket.auth.host, handlerSocket.auth.writePort)

	hsAddress, err := net.ResolveTCPAddr("tcp", targetAddress)
	hsWrAddress, err := net.ResolveTCPAddr("tcp", wrTargetAddress)

	handlerSocket.conn, err = net.DialTCP("tcp", localAddress, hsAddress)
	handlerSocket.wrConn, err = net.DialTCP("tcp", localAddress, hsWrAddress)

	if handlerSocket.Logging {
		log.Print("Connected using TCP/IP")
	}

	handlerSocket.in = make(chan HandlerSocketResponse)
	handlerSocket.out = make(chan HandlerSocketCommandWriter)
	handlerSocket.wrIn = make(chan HandlerSocketResponse)
	handlerSocket.wrOut = make(chan HandlerSocketCommandWriter)

	go handlerSocket.reader(handlerSocket.conn)
	go handlerSocket.writer(handlerSocket.conn)

	go handlerSocket.wrreader(handlerSocket.wrConn)
	go handlerSocket.wrwriter(handlerSocket.wrConn)

	indexes = make(map[int][]string, 10)

	handlerSocket.connected = true
	return
}
コード例 #3
0
ファイル: easynet.go プロジェクト: jmptrader/Tecellate
func Dial(addrString string) *net.TCPConn {
	addr, err := net.ResolveTCPAddr(addrString)
	DieIfError(err, "TCP address resolution error")
	conn, err := net.DialTCP("tcp", nil, addr)
	for err != nil && strings.HasSuffix(err.String(), "connection refused") {
		time.Sleep(10000)
		conn, err = net.DialTCP("tcp", nil, addr)
	}
	DieIfError(err, "Dial error")
	conn.SetNoDelay(true)
	return conn
}
コード例 #4
0
ファイル: util.go プロジェクト: gitHubOffical/gost
func Connect(addr, proxy string) (net.Conn, error) {
	if !strings.Contains(addr, ":") {
		addr += ":80"
	}
	if len(proxy) == 0 {
		taddr, err := net.ResolveTCPAddr("tcp", addr)
		if err != nil {
			log.Println(err)
			return nil, err
		}
		return net.DialTCP("tcp", nil, taddr)
	}

	paddr, err := net.ResolveTCPAddr("tcp", proxy)
	if err != nil {
		return nil, err
	}
	pconn, err := net.DialTCP("tcp", nil, paddr)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	header := http.Header{}
	header.Set("Proxy-Connection", "keep-alive")
	req := &http.Request{
		Method: "CONNECT",
		URL:    &url.URL{Host: addr},
		Host:   addr,
		Header: header,
	}
	if err := req.Write(pconn); err != nil {
		log.Println(err)
		pconn.Close()
		return nil, err
	}

	resp, err := http.ReadResponse(bufio.NewReader(pconn), req)
	if err != nil {
		log.Println(err)
		pconn.Close()
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		pconn.Close()
		return nil, errors.New(resp.Status)
	}

	return pconn, nil
}
コード例 #5
0
ファイル: UDP.go プロジェクト: hakonBG/SanntidsHeis
func Get_own_ip() string {

	googleAddress, _ := net.ResolveTCPAddr("tcp", "www.google.com:80")
	googleConn, err := net.DialTCP("tcp", nil, googleAddress)
	for {
		Println("waitin for IP")
		if err == nil {
			break
		}
		googleConn, err = net.DialTCP("tcp", nil, googleAddress)
	}
	Ip := strings.Split(googleConn.LocalAddr().String(), ":")[0]
	googleConn.Close()
	return Ip
}
コード例 #6
0
ファイル: cluster_test.go プロジェクト: cespare/prat
func (s *S) TestCustomDial(c *C) {
	dials := make(chan bool, 16)
	dial := func(addr net.Addr) (net.Conn, error) {
		tcpaddr, ok := addr.(*net.TCPAddr)
		if !ok {
			return nil, fmt.Errorf("unexpected address type: %T", addr)
		}
		dials <- true
		return net.DialTCP("tcp", nil, tcpaddr)
	}
	info := mgo.DialInfo{
		Addrs: []string{"localhost:40012"},
		Dial:  dial,
	}

	// Use hostname here rather than IP, to make things trickier.
	session, err := mgo.DialWithInfo(&info)
	c.Assert(err, IsNil)
	defer session.Close()

	const N = 3
	for i := 0; i < N; i++ {
		select {
		case <-dials:
		case <-time.After(5 * time.Second):
			c.Fatalf("expected %d dials, got %d", N, i)
		}
	}
	select {
	case <-dials:
		c.Fatalf("got more dials than expected")
	case <-time.After(100 * time.Millisecond):
	}
}
コード例 #7
0
ファイル: writeblock.go プロジェクト: xiaochai/gorpc
func client() {
	addr, err := net.ResolveTCPAddr("tcp", SERVER_ADDR)
	if err != nil {
		panic(err)
	}
	conn, err := net.DialTCP("tcp", nil, addr)
	conn.SetWriteBuffer(WRITE_BUF_SIZE)
	if err != nil {
		panic(err)
	}
	b := make([]byte, WRITE_BLOCK)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	amount := 0
	for i := 1; ; i++ {
		n, e := conn.Write(b)
		if e != nil {
			fmt.Println("client write error: ", e)
			break
		}
		amount += n
		fmt.Println("write amount KB: ", amount/KB, amount)
		// time.Sleep(time.Millisecond)
	}
	fmt.Println("client exit")
}
コード例 #8
0
ファイル: cluster_test.go プロジェクト: Yogesh9692/mgo
func (s *S) TestCustomDialNew(c *C) {
	dials := make(chan bool, 16)
	dial := func(addr *mgo.ServerAddr) (net.Conn, error) {
		dials <- true
		if addr.TCPAddr().Port == 40012 {
			c.Check(addr.String(), Equals, "localhost:40012")
		}
		return net.DialTCP("tcp", nil, addr.TCPAddr())
	}
	info := mgo.DialInfo{
		Addrs:      []string{"localhost:40012"},
		DialServer: dial,
	}

	// Use hostname here rather than IP, to make things trickier.
	session, err := mgo.DialWithInfo(&info)
	c.Assert(err, IsNil)
	defer session.Close()

	const N = 3
	for i := 0; i < N; i++ {
		select {
		case <-dials:
		case <-time.After(5 * time.Second):
			c.Fatalf("expected %d dials, got %d", N, i)
		}
	}
	select {
	case <-dials:
		c.Fatalf("got more dials than expected")
	case <-time.After(100 * time.Millisecond):
	}
}
コード例 #9
0
ファイル: Client.go プロジェクト: zj8487/GoDeploy
func (cl *Client) Connect(addr string) {
	cl.checkConneciton(true, false)
	serverAddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		cl.Printf(fmt.Sprintf("Connect serverAddr Error:%v", err))
		cl.checkConneciton(true, false)
		cl.ClientChan <- "connect serverAddr error"
		return
	}
	con, err := net.DialTCP("tcp", nil, serverAddr)
	if err != nil {
		if *configInfo.Load == "" {
			fmt.Printf("----------------Client[%v]-------------\n", cl.Server)
			fmt.Printf("[type]:%v\n", "Error")
			fmt.Printf("[msg]:%v\n", err)
			fmt.Printf("----------------------------------------------\n")
		} else {
			fmt.Printf("[script]client:%v,type:%v,msg:%v\n", cl.Server, "Error", err)
		}
		cl.checkConneciton(true, false)
		cl.ClientChan <- "connect failed"
		return
	}

	cl.checkConneciton(false, true)
	time.Sleep(time.Second)
	cl.Init(con)
	cl.File = false
	msg := fmt.Sprintf("action:login,user:%s,pwd:%s", cl.User, cl.Pwd)
	//cl.Conn.SetReadDeadline(time.Now().Add(time.Duration(envConfig.Configs.Server.Timeout) * time.Second))
	go cl.Read()
	cl.Write([]byte(msg))
}
コード例 #10
0
ファイル: irc_bot.go プロジェクト: JingxuanWang/Playground
func (b *BotClient) Init(debug bool) {
	// Connect to the server
	addr, err := net.ResolveTCPAddr("tcp", b.host)
	if err != nil {
		b.warn("Unable to resolve TCP Address " + b.host)
	}

	// Dial the socket
	socket, err := net.DialTCP("tcp", nil, addr)
	if err != nil {
		b.warn("Unable to dial socket")
	}

	b.SockReader = bufio.NewReader(socket)
	b.SockWriter = bufio.NewWriter(socket)
	b.ReadChan = make(chan string, 1000)
	b.WriteChan = make(chan string, 1000)
	b.debug = debug
	b.handler_map = make(map[string]*Handler)

	// start goroutine to do this
	go b.startReader()
	go b.startWriter()
	go b.startListener(DEFAULT_LISTENER_PORT)

	b.Connect()
}
コード例 #11
0
ファイル: cstamp018c.go プロジェクト: jelmerdereus/Cstamp
func sendTCP(tslogentry *TSLogEntry, sendTCPstatus chan string) {
	//resolve the *net.TCPAddr of remoteHost
	tcp_address, err := net.ResolveTCPAddr("tcp4", remoteHost)
	if err != nil {
		sendTCPstatus <- fmt.Sprintf("\nCould not resolve TCP address {{ %s }}\n\n", err.Error())
		return
	}

	//make a TCP connection
	tcp_connection, err := net.DialTCP("tcp4", nil, tcp_address)
	if err != nil {
		sendTCPstatus <- fmt.Sprintf("\nTCP connection with remoteHost %s failed:\n\n%s\n", remoteHost, err.Error())
		return
	}
	defer tcp_connection.Close()

	//create an encoder (encodes *TSLogEntry and writes with "\n")
	encoder := json.NewEncoder(tcp_connection)

	//write the message to the TCP port
	err = encoder.Encode(tslogentry)
	if err != nil {
		sendTCPstatus <- fmt.Sprintf("\nTransmission to remoteHost %s failed:\n\n%s\n", remoteHost, err.Error())
		return
	}

	sendTCPstatus <- fmt.Sprintf("\nSent message with ID %s to server %s\n", tslogentry.UniqID, remoteHost)
}
コード例 #12
0
ファイル: connect.go プロジェクト: proudlygeek/proxyg
func proxyConnect(localConn net.Conn, host string) {
	print("Connecting Host %s...\n", host)

	// localAddress, _ := net.ResolveTCPAddr("", "127.0.0.1:8080")
	var localAddress *net.TCPAddr

	remoteAddress, err := net.ResolveTCPAddr("", host)
	if err != nil {
		fmt.Fprint(localConn, "HTTP/1.0 502 Bad Gateway. Address not resolved, baby.\r\n\r\n")
		print("Error: %v", err)
		localConn.Close()
		return
	}

	print("Remote Address: %v", remoteAddress)

	remoteConn, err := net.DialTCP("tcp", localAddress, remoteAddress)
	if remoteConn == nil {
		fmt.Fprint(localConn, "HTTP/1.0 502 Bad Gateway. Connection not established, honey.\r\n\r\n")
		print("Error: %v", err)
		localConn.Close()
		return
	}

	remoteConn.SetKeepAlive(true)
	fmt.Fprint(localConn, "HTTP/1.0 200 CONNECTION ESTABLISHED\r\n\r\n")

	go Copy(localConn, remoteConn)
	go Copy(remoteConn, localConn)
}
コード例 #13
0
ファイル: opentsdb.go プロジェクト: TalkingData/OWL-v3
func (this *OpentsdbBackend) serve() {
	var (
		err       error
		conn      *net.TCPConn
		tempDelay time.Duration
	)
retry:
	conn, err = net.DialTCP("tcp", nil, this.tcpAddr)
	if err != nil {
		if tempDelay == 0 {
			tempDelay = 5 * time.Millisecond
		} else {
			tempDelay *= 2
		}
		if max := 5 * time.Second; tempDelay > max {
			tempDelay = max
		}
		time.Sleep(tempDelay)
		goto retry
	}
	this.session = &session{
		conn:     conn,
		exitFlag: 1,
	}
	for {
		if this.session.IsClosed() {
			goto retry
		}
		time.Sleep(time.Second * 1)
	}
}
コード例 #14
0
ファイル: client.go プロジェクト: ijibu/go-startup
func connect() {
	var tcpAddr *net.TCPAddr
	tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()

	fmt.Println("connected!")
	go onMessageRecived(conn)

	var fDumpCache string = "1s"
	if !(fDumpCache == "") {
		dur, err := time.ParseDuration(fDumpCache)
		if err != nil {
			fmt.Printf("[-] couldn't parse %s: %s\n", fDumpCache, err.Error())
			return
		}
		//每隔五秒钟发送一次消息。
		for {
			msg := time.Now().String()
			b := []byte(msg + "aaaaaaaaaaa\n")
			fmt.Println(string(b))
			conn.Write(b)
			//time.Sleep()表示休眠多少时间,休眠时处于阻塞状态,后续程序无法执行.
			//time.After()表示多少时间之后,但是在取出channel内容之前不阻塞,后续程序可以继续执行。
			<-time.After(dur)
		}
	}
}
コード例 #15
0
ファイル: net.go プロジェクト: tuhuayuan/go.xmpp
// Dial opens a new TCP connection with XMPP-style peer discovery.
// Typically, Dial is not called directly but instead called when necessary by the stream object.
func Dial(domain, service string, defaultPort uint16) (*net.TCPConn, error) {
	_, srvs, err := net.LookupSRV(service, "tcp", domain)

	// Try fallback process if SRV lookup fails
	if err != nil {
		addr, err := net.ResolveTCPAddr("tcp", fmt.Sprint(domain, ":", defaultPort))
		if err != nil {
			return nil, err
		}
		return net.DialTCP("tcp", addr, nil)
	}

	if len(srvs) == 1 && srvs[0].Target == "." {
		return nil, errors.New("dial: '" + service + "' service does not exist at " + domain)
	}

	for _, srv := range srvs {
		conn, err := dialRecord(srv)
		if err == nil {
			return conn, err
		}
	}

	return nil, errors.New("dial: the server '" + domain + "' failed to respond.")
}
コード例 #16
0
ファイル: back_client.go プロジェクト: neutony/gotunnel
func (self *BackClient) Start() error {
	upstream, err := self.readSettings()
	if err != nil {
		return err
	}
	self.upstream = upstream

	addr, err := net.ResolveTCPAddr("tcp", self.backAddr)
	if err != nil {
		return err
	}
	conn, err := net.DialTCP("tcp", nil, addr)
	if err != nil {
		return err
	}

	err = writeTGW(conn)
	if err != nil {
		Error("write tgw failed")
		return err
	}

	self.coor = NewCoor(NewTunnel(conn), self)

	self.wg.Add(1)
	go self.pump()
	return nil
}
コード例 #17
0
ファイル: connection.go プロジェクト: evangineer/Go-Redis
// Creates and opens a new connection to server per ConnectionSpec.
// The new connection is wrapped by a new connHdl with its bufio.Reader
// delegating to the net.Conn's reader. 
//
func newConnHdl (spec *ConnectionSpec) (hdl *connHdl, err os.Error) {
	here := "newConnHdl";

	if hdl = new(connHdl); hdl == nil { 
		return nil, withNewError (fmt.Sprintf("%s(): failed to allocate connHdl", here));
	}
	addr := fmt.Sprintf("%s:%d", spec.host, spec.port); 
	raddr, e:= net.ResolveTCPAddr(addr); 
	if e != nil {
		return nil, withNewError (fmt.Sprintf("%s(): failed to resolve remote address %s", here, addr));
	}	
	conn, e:= net.DialTCP(TCP, nil, raddr);
	switch {
		case e != nil:
			err = withOsError (fmt.Sprintf("%s(): could not open connection", here), e);
		case conn == nil:
			err = withNewError (fmt.Sprintf("%s(): net.Dial returned nil, nil (?)", here));
		default:
			configureConn(conn, spec);
			hdl.spec = spec;
			hdl.conn = conn;
			bufsize := 4096;
			hdl.reader, e = bufio.NewReaderSize(conn, bufsize);
			if e != nil {
				err = withNewError (fmt.Sprintf("%s(): bufio.NewReaderSize (%d) error", here, bufsize));
			}
			else {
				if debug() {log.Stdout("[Go-Redis] Opened SynchConnection connection to ", addr);}
			}
	}
	return hdl, err;
}
コード例 #18
0
func isListening(uri string) bool {
	address, err := net.ResolveTCPAddr("tcp", uri)
	Expect(err).ToNot(HaveOccurred())

	_, err = net.DialTCP("tcp", nil, address)
	return err == nil
}
コード例 #19
0
ファイル: gethead.go プロジェクト: ngpeijiun/sample-code-go
func main() {
	checkArgs(os.Args)

	service := os.Args[1]

	addr, err := net.ResolveTCPAddr("tcp", service)

	checkError(err)

	conn, err := net.DialTCP("tcp", nil, addr)

	checkError(err)

	defer conn.Close()

	_, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))

	checkError(err)

	result, err := ioutil.ReadAll(conn)

	checkError(err)

	fmt.Println(string(result))
}
コード例 #20
0
func main() {

	if len(os.Args) < 3 {
		fmt.Printf("usage ./transferclient <filename> <savefilename\n")
		return
	}
	service := "127.0.0.1:8010"
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	if err != nil {
		fmt.Printf("ResolveTCPAddr")
	}
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		fmt.Printf("DialTcp error,%s\n", err)
	} else {
		session := socket.NewTcpSession(conn)
		fmt.Printf("connect sucessful\n")
		//发出文件请求
		wpk := packet.NewWPacket(packet.NewByteBuffer(64))
		wpk.PutUint16(request_file)
		wpk.PutString(os.Args[1])
		session.Send(wpk)
		tsession := &transfer_session{filename: os.Args[2]}
		session.SetUd(tsession)
		socket.ProcessSession(session, packet.NewRPacketDecoder(65535), process_client)
	}
}
コード例 #21
0
ファイル: client.go プロジェクト: wmydz1/protobuf_example
func main() {
	regMessage := &example.RegMessage{
		Id:       proto.Int32(10001),
		Username: proto.String("vicky"),
		Password: proto.String("123456"),
		Email:    proto.String("*****@*****.**"),
	}

	fmt.Println(regMessage)

	buffer, err := proto.Marshal(regMessage)
	if err != nil {
		fmt.Printf("failed: %s\n", err)
		return
	}

	pTCPAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:10000")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
		return
	}
	pTCPConn, err := net.DialTCP("tcp", nil, pTCPAddr)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
		return
	}
	pTCPConn.Write(buffer)
}
コード例 #22
0
ファイル: mmd.go プロジェクト: mvander3/go-mmd
func _create_connection(cfg *Config) (*Conn, error) {
	addr, err := net.ResolveTCPAddr("tcp", cfg.Url)
	if err != nil {
		return nil, err
	}
	// log.Printf("Connecting to: %s / %s\n", cfg.url, addr)
	conn, err := net.DialTCP("tcp", nil, addr)
	if err != nil {
		return nil, err
	}
	conn.SetWriteBuffer(cfg.WriteSz)
	conn.SetReadBuffer(cfg.ReadSz)
	mmdc := &Conn{socket: conn,
		writeChan:   make(chan []byte),
		dispatch:    make(map[ChannelId]chan ChannelMsg, 1024),
		callTimeout: time.Second * 5,
		services:    make(map[string]ServiceFunc),
	}
	go writer(mmdc)
	go reader(mmdc)
	handshake := []byte{1, 1}
	handshake = append(handshake, cfg.AppName...)
	mmdc.WriteFrame(handshake)
	return mmdc, nil
}
コード例 #23
0
ファイル: opentsdb.go プロジェクト: ronaldslc/telegraf
func (o *OpenTSDB) Write(points []*client.Point) error {
	if len(points) == 0 {
		return nil
	}
	now := time.Now()

	// Send Data with telnet / socket communication
	uri := fmt.Sprintf("%s:%d", o.Host, o.Port)
	tcpAddr, _ := net.ResolveTCPAddr("tcp", uri)
	connection, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		return fmt.Errorf("OpenTSDB: Telnet connect fail")
	}
	defer connection.Close()

	for _, pt := range points {
		for _, metric := range buildMetrics(pt, now, o.Prefix) {
			messageLine := fmt.Sprintf("put %s %v %s %s\n",
				metric.Metric, metric.Timestamp, metric.Value, metric.Tags)
			if o.Debug {
				fmt.Print(messageLine)
			}
			_, err := connection.Write([]byte(messageLine))
			if err != nil {
				return fmt.Errorf("OpenTSDB: Telnet writing error %s", err.Error())
			}
		}
	}

	return nil
}
コード例 #24
0
ファイル: dialer.go プロジェクト: airmao/v2ray-core
func Dial(dest v2net.Destination) (net.Conn, error) {
	var ip net.IP
	if dest.Address().IsIPv4() || dest.Address().IsIPv6() {
		ip = dest.Address().IP()
	} else {
		ips, err := net.LookupIP(dest.Address().Domain())
		if err != nil {
			return nil, err
		}
		if len(ips) == 0 {
			return nil, ErrInvalidHost
		}
		ip = ips[dice.Roll(len(ips))]
	}
	if dest.IsTCP() {
		return net.DialTCP("tcp", nil, &net.TCPAddr{
			IP:   ip,
			Port: int(dest.Port()),
		})
	} else {
		return net.DialUDP("udp", nil, &net.UDPAddr{
			IP:   ip,
			Port: int(dest.Port()),
		})
	}
}
コード例 #25
0
ファイル: xymonc.go プロジェクト: tjyang/abmon
// ---------------------------- MAIN           ---------------------------
func main() {

	// ---------------------------- VARIABLES DECLARATION ---------------------------
	var usage string = "Usage: %s host:port \n"
	var httpheader string = "HEAD / HTTP/1.0\r\n\r\n"

	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, usage, os.Args[0])
		os.Exit(1)
	}
	service := os.Args[1]

	tcpAddr, err := net.ResolveTCPAddr("tcp", service)
	checkError(err)

	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	checkError(err)

	// case port 80
	_, err = conn.Write([]byte(httpheader))
	checkError(err)
	// case port 80
	result, err := ioutil.ReadAll(conn)
	checkError(err)
	fmt.Println(string(result))

	os.Exit(0)
}
コード例 #26
0
ファイル: rawclient.go プロジェクト: jonpugh/maggiefs
func newRawClient(addr string) (*rawclient, error) {
	tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		return nil, err
	}
	fmt.Printf("connecting to %s\n", addr)
	c, err := net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		return nil, err
	}
	fmt.Println("connected")
	c.SetNoDelay(true)
	c.SetKeepAlive(true)
	idBuff := make([]byte, 8, 8)
	_, err = c.Read(idBuff)
	if err != nil {
		return nil, err
	}
	ret := &rawclient{binary.LittleEndian.Uint64(idBuff), c, 0, make(chan maggiefs.NotifyEvent, 100), make(chan queuedRequest), make(chan response), make(chan bool)}
	// read client id

	go ret.mux()
	go ret.readResponses()
	return ret, nil
}
コード例 #27
0
ファイル: socket.go プロジェクト: admpub/server
func newActiveSocket(remote string, port int, logger *Logger) (DataSocket, error) {
	connectTo := net.JoinHostPort(remote, strconv.Itoa(port))

	logger.Print("Opening active data connection to " + connectTo)

	raddr, err := net.ResolveTCPAddr("tcp", connectTo)

	if err != nil {
		logger.Print(err)
		return nil, err
	}

	tcpConn, err := net.DialTCP("tcp", nil, raddr)

	if err != nil {
		logger.Print(err)
		return nil, err
	}

	socket := new(ftpActiveSocket)
	socket.conn = tcpConn
	socket.host = remote
	socket.port = port
	socket.logger = logger

	return socket, nil
}
コード例 #28
0
ファイル: Agent.go プロジェクト: cokeboL/ZIM
func dial(addr string) (*net.TCPConn, error) {
	var conn *net.TCPConn
	var err error
	var count = 0
	var tcpAddr *net.TCPAddr
	if tcpAddr, err = net.ResolveTCPAddr("tcp4", addr); err != nil {
		return nil, err
	}

	for {
		count++
		if count > NetConf.MAX_DIAL_TIMES {
			return nil, err
		}

		conn, err = net.DialTCP("tcp", nil, tcpAddr)

		Logger.Info(LogConf.NetCoreAgent, LogConf.SERVER, "Agent dial time: %d addr %s %v", count, addr, conn)
		if err == nil {
			return conn, nil
		}

		time.Sleep(NetConf.DIAL_INTERNAL)
	}

	return nil, nil
}
コード例 #29
0
ファイル: main.go プロジェクト: robertojrojas/networking-Go
func main() {

	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s host:port\n", os.Args[0])
		os.Exit(1)
	}

	service := os.Args[1]

	// There may be syntax errors in the address specified
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError(err)

	// The attempt to connect to the remote service may fail.
	// For example, the service requested might not be running,
	// or there may be no such host connected to the network
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	checkError(err)

	// Although a connection has been established,
	// writes to the service might fail if the connection has died suddenly,
	// or the network times out
	_, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
	checkError(err)

	// Similarly, the reads might fail
	result, err := ioutil.ReadAll(conn)
	checkError(err)

	fmt.Println(string(result))

	os.Exit(0)
}
コード例 #30
0
ファイル: connection.go プロジェクト: r0m1bl/Go-Redis
// Creates and opens a new connection to server per ConnectionSpec.
// The new connection is wrapped by a new connHdl with its bufio.Reader
// delegating to the net.Conn's reader.
//
func newConnHdl(spec *ConnectionSpec) (hdl *connHdl, err Error) {
	here := "newConnHdl"

	if hdl = new(connHdl); hdl == nil {
		return nil, NewError(SYSTEM_ERR, fmt.Sprintf("%s(): failed to allocate connHdl", here))
	}
	addr := fmt.Sprintf("%s:%d", spec.host, spec.port)
	raddr, e := net.ResolveTCPAddr(addr)
	if e != nil {
		msg := fmt.Sprintf("%s(): failed to resolve remote address %s", here, addr)
		return nil, NewErrorWithCause(SYSTEM_ERR, msg, e)
	}
	conn, e := net.DialTCP(TCP, nil, raddr)
	switch {
	case e != nil:
		err = NewErrorWithCause(SYSTEM_ERR, fmt.Sprintf("%s(): could not open connection", here), e)
	case conn == nil:
		err = NewError(SYSTEM_ERR, fmt.Sprintf("%s(): net.Dial returned nil, nil (?)", here))
	default:
		configureConn(conn, spec)
		hdl.spec = spec
		hdl.conn = conn
		bufsize := 4096
		hdl.reader, e = bufio.NewReaderSize(conn, bufsize)
		if e != nil {
			msg := fmt.Sprintf("%s(): bufio.NewReaderSize (%d) error", here, bufsize)
			err = NewErrorWithCause(SYSTEM_ERR, msg, e)
		} else {
			if err = hdl.onConnect(); err == nil && debug() {
				log.Stdout("[Go-Redis] Opened SynchConnection connection to ", addr)
			}
		}
	}
	return hdl, err
}