Go语言网络通信---tcp群发消息
Posted yunweiqiang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)) }
以上是关于Go语言网络通信---tcp群发消息的主要内容,如果未能解决你的问题,请参考以下文章