英文:
Can we use select to Accept() from different listeners in Go?
问题
就像以下代码一样:
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)
}
}
当编辑器告诉我select
有问题时,我们能在Go中实现类似这样的代码吗?
英文:
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?
答案1
得分: 1
select
只能用于通道(在这里了解更多:https://gobyexample.com/select)
在你的情况下,你可以创建两个goroutine,每个goroutine等待一个监听器的Accept
并处理连接:
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)
}
}()
英文:
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)
}
}()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论