[Daily] Go Language Bible--Concurrent Loop Exercises

Exercise 8.4: Modify the reverb2 server to use sync.WaitGroup to count active echo goroutines per connection. When the count reaches zero, close the TCP connection for writing, as in Exercise 8.3. Verify that your modified netcat3 client will always wait for all concurrent "shouting" to complete, even when the standard input stream has been closed.

 

Important: Wait for all goroutines to complete before closing the TCP connection

package main

import (
        "bufio"
        "fmt"
        "log"
        "net"
        "strings"
        "time"
        "sync"
)

func main() {
        listener, err := net.Listen("tcp", ":8040")
        if err != nil {
                log.Fatal(err)
        }   

        for {
                conn, err := listener.Accept()
                if err != nil {
                        log.Print(err) // e.g., connection aborted
                        continue
                }   
                go handleConn(conn) //Create new goroutines to handle the connection
        }   
}

func handleConn(c net.Conn) {
        input := bufio.NewScanner(c)
        var wg sync.WaitGroup
        //var  ch =make(chan struct{})
        for input.Scan() {
                wg.Add(1)
                go func(c net.Conn, shout string, delay time.Duration) {
                        defer wg.Done()
                        fmt.Fprintln(c, "\t", strings.ToUpper(shout))
                        time.Sleep(delay)
                        fmt.Fprintln(c, "\t", shout)
                        time.Sleep(delay)
                        fmt.Fprintln(c, "\t", strings.ToLower(shout))
                        //ch<-struct{}{}

                }(c, input.Text(), 1*time.Second)
        }   
        wg.Wait()
                //cw := c.(*net.TCPConn)
          //cw.CloseWrite()
        
        c.Close()
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325227957&siteId=291194637