本文共 1105 字,大约阅读时间需要 3 分钟。
/ server.go /
package mainimport (
"fmt""net""os")func checkError(err error) {
if err != nil { fmt.Println("Error: %s", err.Error())os.Exit(1)}}func recvUDPMsg(conn *net.UDPConn) {
var buf [20]byten, raddr, err := conn.ReadFromUDP(buf[0:]) if err != nil { return } fmt.Println("msg is ", string(buf[0:n])) //WriteToUDP //func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error) _, err = conn.WriteToUDP([]byte("nice to see u"), raddr) checkError(err)
}
func main() {
udp_addr, err := net.ResolveUDPAddr("udp", ":9098")checkError(err)conn, err := net.ListenUDP("udp", udp_addr) defer conn.Close() checkError(err) //go recvUDPMsg(conn) for { recvUDPMsg(conn) }
}
/ client.go /
package mainimport (
"fmt""net""os"// "io")func main() {
conn, err := net.Dial("udp", "127.0.0.1:9098")defer conn.Close()if err != nil { os.Exit(1)}conn.Write([]byte("Hello world!")) fmt.Println("send msg") var msg [20]byte conn.Read(msg[0:]) fmt.Println("msg is", string(msg[0:10]))
}
转载于:https://blog.51cto.com/4488415/2071334