tcp客户端结束时没有达到某些语句

时间:2015-02-27 04:29:42

标签: tcp go

下面的代码假设打开与服务器的连接,发送消息并在结束前等待回复,但问题是它甚至没有到达函数的末尾。可能有什么不对?我应该使用wg sync.WaitGroup吗?

func client(servId uint16, servAddr string) {

    tcpAddr, err := net.ResolveTCPAddr("tcp", servAddr)
    check(err)

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

    _, err = conn.Write(handshake(servId, 1500))
    check(err)

    init := make([]byte, 8)
    _, err = io.ReadFull(conn, init)
    check(err)

    fmt.Println("is reached") // doesn't get printed WHY?
    fmt.Println(init)
}

如何从main

调用上述函数
// vars
var c, startId, servId uint16

// for each servers
for s := 0; s < len(config.Servers); s++ {

    // for each connection
    for c = 0; c < config.Total_clients; c++ {

        startId = config.Server_id * config.Total_clients
        servId = startId + c

        servAddr := fmt.Sprintf("%s:%d", config.Servers[s].Host, config.Servers[s].Port)

        // create the clients in new go routines
        go client(servId, servAddr)
    }

}

1 个答案:

答案 0 :(得分:0)

您的程序将在完成执行之前退出,您需要使用sync.WaitGroup或通道等待所有输出才能退出。

func client(wg *sync.WaitGroup, servId uint16, servAddr string) {
    defer wg.Done()
.....
}

func main() {
    var (
        c, startId, servId uint16
        wg                 sync.WaitGroup
    )
    for _, srv := range config.Servers {
        for c = 0; c < config.Total_clients; c++ {
        ......
            wg.Add(1)
            go client(&wg, servId, servAddr)
        }
    }
    wg.Wait()
}