dongyuan1983 2019-04-09 15:32
浏览 148
已采纳

如何编写在goroutine中执行的函数以发送和接收消息?

I have to write a client side code that is receiving messages in the form of strings from server as well as taking input from the console to end message to the server. Both these operations should run concurrently with each other. I have written a code which perform these operations but sequentially not concurrently.

Here's what my current code looks like:

func SocketClient() {
    conn, err := net.Dial("tcp", ":9000")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()
    server_reader := bufio.NewReader(conn)
    input_reader := bufio.NewReader(os.Stdin)
    for {
        // for sending messages
        buff, err := input_reader.ReadString('
')
        if err != nil {
            log.Fatalln(err)
        }
        conn.Write([]byte(buff))

        // for receiving messages but this won't run until the above has taken input from console
        buff2, err := server_reader.ReadString('
')
        if err != nil {
            log.Fatalln(err)
        }
        fmt.Println("Received: %s", buff2)
    }
}

buff receives incoming messages from server and then buff2 takes outgoing message input from console but in order to receive the incoming messages again, buff2 needs some input. I know this can be done using channels, mutex locks etc. but because of my lack of understanding of fundamentals I am having problem using them.

I guess the actual code should look something like this:

func SocketClient() {
    conn, err := net.Dial("tcp", ":9000")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()
    go func() {
        // for sending messages
    } ()
    go func() {
        // for receiving messages
    } ()
}

How to make the input and output as two separate goroutines?

  • 写回答

3条回答 默认 最新

  • dru5089 2019-04-09 16:39
    关注

    Run one of the loops directly in SocketClient. Run the other loop in a new goroutine started by SocketClient.

    func SocketClient() error {
        conn, err := net.Dial("tcp", ":9000")
        if err != nil {
            return err
        }
        defer conn.Close()
        server_reader := bufio.NewReader(conn)
        input_reader := bufio.NewReader(os.Stdin)
    
        go func() {
            defer conn.Close()
    
            // This loop will break and the goroutine will exit when the
            // SocketClient function executes conn.Close().
    
            for {
                buff, err := server_reader.ReadBytes('
    ')
                if err != nil {
                    // optional: log.Fatal(err) to cause program to exit without waiting for new input from stdin.
                    return
                }
                fmt.Printf("Received: %s", buff)
            }
        }()
    
        for {
            // for sending messages
            buff, err := input_reader.ReadBytes('
    ')
            if err != nil {
                return err
            }
            if _, err := conn.Write(buff); err != nil {
                return err
            }
        }
    }
    

    Use the bufio.Reader ReadBytes method instead of the ReadString to avoid unnecessary conversions between []byte and string.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongqie2028 2019-04-09 16:17
    关注

    You can create a function like this one, that returns a channel. It also starts a new go routine that will write to the returned channel.

    This allows consumers to call this method, and expect values back on the returned channel.

    I've also updated the method signature to use a *bufio.Scanner as it's a more efficient method of splitting on newlines.

    func ReadFully(scanner *bufio.Scanner) <-chan string {
        out := make(chan  string)
    
        go func() {
            // once all the values have been read, close the channel
            // this tells the consumers that there will not be anymore
            // values and they don't need to keep listening to this channel.
            defer close(out)
    
            for scanner.Scan() {
                out <- scanner.Text()
            }
    
            if err := scanner.Err(); err!= nil {
                log.Fatal(err)
            }
        }()
    
        return out
    }
    

    Now we can use this ReadFully method in SocketClient

    func SocketClient() {
        conn, err := net.Dial("tcp", ":9000")
        if err != nil {
            log.Fatal(err)
        }
        defer conn.Close()
    
        serverScan := bufio.NewScanner(conn)
        inputScan := bufio.NewScanner(os.Stdin)
    
    
        serverCh := ReadFully(serverScan)
        inputCh := ReadFully(inputScan)
    
    
        // create a wait group, this stops the SocketClient 
        // method from exiting until the workers are done.
        var wg sync.WaitGroup
        wg.Add(2)
    
        go func() {
            defer wg.Done()
            for v := range inputCh {
                _, _ = conn.Write([]byte(v))
            }
        }()
    
        go func() {
            defer wg.Done()
            for v := range serverCh {
                fmt.Printf("Received: %s
    ", v)
            }
        }()
    
        wg.Wait()
    }
    
    

    Note, this example entirely omits cancellations etc. In general you should never start a go routine without a way to stop it.

    Check out this great article on pipelines. https://blog.golang.org/pipelines

    评论
  • duaevb1511 2019-04-11 20:11
    关注

    I wrote a blog post on Go concurrency. https://marcofranssen.nl/concurrency-in-go/

    also used some of the concepts in this blog post.

    https://marcofranssen.nl/go-webserver-with-gracefull-shutdown/

    which also allows me to intercept commandline input like signals to safely shutdown the server.

    You might use a similar approach to take your commanding input and user it.

    The main idea is to use channels for communicating between your go routines.

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用matlab进行手眼标定的仿真验证,得到齐次矩阵与opencv相差较大
  • ¥15 Python词频统计,运行出的Excel没有内容
  • ¥15 求推荐一个好用的录屏软件
  • ¥15 kali显示no x11 display variable was set;
  • ¥15 如何实现这个Python开发问题
  • ¥15 Erasure Code纠删码表
  • ¥15 用vite创建的vue3项目,404重定向不起作用??
  • ¥15 关于#c语言#的问题:一个球从80米高度自由落下,每次落地后反弹的高度为原高度的一半计算6次小球反弹的高度.(反弹结果取整,使用走走for循环结构)
  • ¥15 SurfaceControl的screenshot问题
  • ¥15 基于51单片机的oled菜单代码,要C语言,模块化编程!