转到:在tcp侦听器运行时允许键盘输入

I'm writing an application which should both listen for incoming TCP connections, but also send TCP packets when requested.

I have a simple Listen function, which accepts the incoming connections

func (a *App) Listen() {
    for {
        conn, err := a.listener.Accept()

        if err != nil {
            // log error
        } else {
            go ProcessConn(conn)
        }
    }
}

I also have a Send function which performs the dialing in order to send a TCP packet

func (a *App) Send(message []byte, host string, port string) error {

    conn, err := net.Dial("tcp", host+":"+port)

    if err != nil {
        return err
    } else {
        defer conn.Close()
    }

    _, err = conn.Write(message)
    return err
}

Now, when I start my app using the Start function it runs an infinite loop (for the listening for incoming connections), so from the perspective of the terminal the program 'freezes' and does not react to any keyboard operations (expect the CTRL-C).

func (a *App) Start() error {

    defer a.Listen()

    // perform some unrelated operations

    return nil
}

However, I would like to improve my app, in such a way, that it can take users (keyboard) input in order to notify my app that it should send a message (I want the users to be able to give the parameters: message and address of the destination.) I was reading about select statement here: https://gobyexample.com/select. and wanted to use it for my app.

This is what I wrote based on the example from the go website:

func UserReacted(c2 chan string){
    for {
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Enter text: ")
        text, _ := reader.ReadString('
')
        c2 <- text
    }
}

func main() {

    a := NewApp()
    a.Start()

    c1 := make(chan string)
    c2 := make(chan string)

    go func() {
        UserReacted(c2)
    }()


    for {
        select {
        case msg2 := <-c2:
            a.Send() // with some parameters added later
        default:
        }
    }
    <-finish
}

I understand how the example from the go website works, but I don't know how to use select when one of the function, in my example the Listen function, is not returning any value. I will be very grateful for any advice or example how to do it properly.