一个简单的golang实现的私聊,由服务器端决定两两匹配
服务器端 chat_server.go
package main import ( "fmt" "io" "log" "net" ) const listenAddr = "localhost:4000" func main() { l,err := net.Listen("tcp",listenAddr) if err != nil { log.Fatal(err) } for { c,err := l.Accept() if err != nil { log.Fatal(err) } //go io.Copy(c,c) 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) } } /* 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) } */ func chat(a,"Found one! Say hi.") errc := make(chan error,1) go cp(a,b,errc) go cp(b,a,errc) if err := <-errc; err != nil { log.Println(err) } a.Close() b.Close() } func cp(w io.Writer,r io.Reader,errc chan<- error) { _,err := io.Copy(w,r) errc <- err }
客户端chat_client.go:
package main import ( "fmt" "log" "net" ) func main() { l,err := net.Dial("tcp","localhost:4000") if err != nil { log.Fatal(err) } go send(l) for { datas := make([]byte,255) n,err := l.Read(datas) if err != nil { log.Fatal(err) } fmt.Println(string(datas[0:n])) } } func send(l net.Conn){ sms := make([]byte,255) for{ //fmt.Print("请输入要发送的消息:") _,err := fmt.Scan(&sms) if err != nil { fmt.Println("数据输入异常:",err.Error()) } l.Write(sms) } }