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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器