This is a creation in Article, where the information may have evolved or changed.
A simple Golang implementation of private chat, determined by server-side 22 matches
Server-Side Chat_server.go
Package Mainimport ("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, b io. Readwritecloser) {fmt. Fprintln (A, "Found one! Say hi. ") Fmt. Fprintln (b, "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}
Client Chat_client.go:
package mainimport ( "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) }}