Go语言网络通信---tcp群发消息
server
package main import ( "fmt" "net" "os" "time" ) func SHandleError(err error, when string) { if err != nil{ fmt.Println("err=", err, when) os.Exit(1) } } func main() { listener, e := net.Listen("tcp", ":8080") SHandleError(e,"net.Listen") conns := make([]net.Conn, 0) for len(conns) < 3 { conn, e := listener.Accept() SHandleError(e, "listener.Accept") conns = append(conns, conn) } fmt.Println("已接入3个客户端,即将群发消息") time.Sleep(time.Second*1) for _,conn:=range conns{ msg := fmt.Sprintf("hello!%v", conn.RemoteAddr()) conn.Write([]byte(msg)) } var userInput = "" fmt.Scan(&userInput) }
client
package main import ( "fmt" "net" "os" ) func CHandleError(err error, when string) { if err != nil{ fmt.Println("err=", err, when) os.Exit(1) } } func main() { conn, e := net.Dial("tcp", "127.0.0.1:8080") CHandleError(e, "net.Dial") defer func() { conn.Close() fmt.Println("客户端已退出") }() buffer := make([]byte, 1024) n, e := conn.Read(buffer) CHandleError(e ,"conn.Read") msg := buffer[:n] fmt.Println(string(msg)) }