I have the following piece of code that implements a simple tcp chat server written in go. I have trouble understanding where in the code the connection is sent through the "partner channel". I see that when the first user connects, the select statement just waits until the next user joins. But when the second user joins, how does the code send information through the channel and know to select which case?
package main
import (
"io"
"net"
"log"
"fmt"
)
const listnAddr = "localhost:4000"
func main(){
l , err := net.Listen("tcp",listnAddr)
if err != nil {
log.Fatal(err)
}
for {
c , err := l.Accept()
if c!= nil{
fmt.Printf("ok")
}
if err != nil {
log.Fatal(err)
}
go match(c)
}
}
var partner = make(chan io.ReadWriteCloser)
func match(c io.ReadWriteCloser){
fmt.Fprint(c,"waiting for a partner...")
select{
case partner <- c:
//now handled by the other goroutine
case p := <-partner:
chat(p,c)
}
fmt.Printf("waiting")
}
func chat(a, b io.ReadWriteCloser) {
fmt.Fprintln(a, "Found one! Say hi.")
fmt.Fprintln(b, "Found one! Say hi.")
go io.Copy(a, b)
io.Copy(b, a)
}
</div>