Can we use select to Accept() from different listeners in Go?

Issue

Just as the following codes:

for {
    select {
    case conn, err := listener1.Accept():
        if err != nil {
            log.Fatal(err)
        }
        go handleConn1(conn)
    case conn, err := listener2.Accept():
        if err != nil {
            log.Fatal(err)
        }
        go handleConn1(conn)
    }
}

While the editor tells me something wrong with select

Can we implement something like this in Go?

Solution

select only works with channels (see more here: https://gobyexample.com/select)

In your case, you could span two goroutines so that each of them waits for the Accept of one listener and processes the connection:

go func() {
    for {
        conn, err := listener1.Accept():
        if err != nil {
            log.Fatal(err)
        }
        handleConn1(conn)
    }
}()
go func () {
    for {
        conn, err := listener2.Accept():
        if err != nil {
            log.Fatal(err)
        }
        handleConn2(conn)
    }
}()

Answered By – eugenioy

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.