代码展示
服务端
package main import ( "fmt" "net" "strings" ) func main(){ Conn,err:=net.ListenUDP("udp",&net.UDPAddr{ IP: net.IPv4(127,0,0,1), Port: 40000, }) if err != nil { fmt.Println("listen udp is error") return } var data [1024]byte for { n,Addr,_:=Conn.ReadFromUDP(data[:]) msg:=string(data[:n]) newmsg:=strings.ToUpper(msg) Conn.WriteToUDP([]byte(newmsg),Addr) } }
客户端代码
package main import ( "bufio" "fmt" "log" "net" "os" ) func main(){ socket,err:=net.DialUDP("udp",nil,&net.UDPAddr{ IP : net.IPv4(0,0,0,0), Port: 40000, }) if err != nil { log.Fatal("is erros") } defer socket.Close() var reply [1024]byte for { reader:= bufio.NewReader(os.Stdin) msg,_:= reader.ReadString('\n') socket.Write([]byte(msg)) n,_,err:= socket.ReadFromUDP(reply[:]) if err != nil { fmt.Println("is error") } msgData:= string(reply[:n]) fmt.Printf("%v\n",msgData) } }