本文整理汇总了Golang中net.DialTCP函数的典型用法代码示例。如果您正苦于以下问题:Golang DialTCP函数的具体用法?Golang DialTCP怎么用?Golang DialTCP使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DialTCP函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ping
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: connect
/**
* 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: Dial
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: Connect
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: Get_own_ip
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: TestCustomDial
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: client
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: TestCustomDialNew
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: Connect
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: Init
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: sendTCP
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: proxyConnect
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: serve
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: connect
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: Dial
// 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.")
}