在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Server端: package main import ( "fmt" "net" ) func main() { //创建udp地址 udpAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:8080") //服务端建立监听 serverConn, _ := net.ListenUDP("udp", udpAddr) defer func() { serverConn.Close() fmt.Println("main over!") }() //与客户端IO buffer := make([]byte, 1024) n, remoteAddress, _ := serverConn.ReadFromUDP(buffer) contents := buffer[:n] fmt.Println("客户端:"+string(contents)) //回复客户端消息 serverConn.WriteToUDP([]byte("孽障!"),remoteAddress) }
Client端: package main import ( "fmt" "net" ) func main() { conn, _ := net.Dial("udp", "127.0.0.1:8080") defer func() { conn.Close() fmt.Println("客户端已退出") }() //客户端发起交谈 conn.Write([]byte("你妹,今天天气不错")) //接收服务端消息 buffer := make([]byte, 1024) n, _ := conn.Read(buffer) fmt.Println("服务端:"+string(buffer[:n])) }
|
请发表评论