2014-10-11 131 views
0

我試圖寫Golang一個簡單的客戶端,但只要我運行它退出,Golang TCP客戶端退出

package main 

    import (
     "fmt" 
     "net" 
     "os" 
     "bufio" 
     "sync" 
    ) 

    func main() { 

     conn, err := net.Dial("tcp", "localhost:8081") 
     if err != nil { 
      fmt.Println(err); 
      conn.Close(); 
     } 
     fmt.Println("Got connection, type anything...new line sends and quit quits the session"); 
     go sendRequest(conn) 
    } 


    func sendRequest(conn net.Conn) { 

     reader := bufio.NewReader(os.Stdin) 
     var wg sync.WaitGroup 
     for { 
      buff := make([]byte, 2048); 
      line, err := reader.ReadString('\n') 
      wg.Add(1); 
      if err != nil { 
       fmt.Println("Error while reading string from stdin",err) 
       conn.Close() 
       break; 
      } 

      copy(buff[:], line) 
      nr, err := conn.Write(buff) 
      if err != nil { 
       fmt.Println("Error while writing from client to connection", err); 
       break; 
      } 
      fmt.Println(" Wrote : ", nr); 
      wg.Done() 
      buff = buff[:0] 
     } 
     wg.Wait() 

    } 

,並試圖運行它的時候,我得到了作爲輸出以下

Got connection, type anything...new line sends and quit quits the session 

Process finished with exit code 0 

我在期待代碼會使stdin(終端)打開並等待輸入文本,但它會立即退出。我是否應該用別的代碼替換stdin中的其他代碼

+0

的問題是,隨走,不等待運行的程序去完成。使用一個等待組。 – Kiril 2014-10-11 12:11:17

+0

@Kiril嘗試使用WaitGroup仍然存在相同問題的建議 – 2014-10-11 13:40:23

+0

如何?更新你的代碼。 – Kiril 2014-10-11 13:42:22

回答

1

main函數返回時,Go程序將退出。

簡單的修復方法是直接撥打sendRequest。該程序中不需要goroutine。

func main() { 

    conn, err := net.Dial("tcp", "localhost:8081") 
    if err != nil { 
    fmt.Println(err); 
    conn.Close(); 
    } 
    fmt.Println("Got connection, type anything...new line sends and quit quits the session"); 
    sendRequest(conn) // <-- go removed from this line. 
} 

如果需要夠程,然後用sync.WaitGroup,使main等待夠程完成:

func main() { 
    conn, err := net.Dial("tcp", "localhost:8081") 
    if err != nil { 
    fmt.Println(err); 
    conn.Close(); 
    } 
    var wg sync.WaitGroup 
    fmt.Println("Got connection, type anything...new line sends and quit quits the session"); 
    wg.Add(1) 
    go sendRequest(&wg, conn) 
    wg.Wait() 
} 

func sendRequest(wg *sync.WaitGroup, conn net.Conn) { 
    defer wg.Done() 
    // same code as before 
}