我们可以在Go中使用select来从不同的监听器中接受连接吗?

huangapple go评论68阅读模式
英文:

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)
    }
}()

huangapple
  • 本文由 发表于 2017年9月10日 16:50:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/46138902.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定