UDP 理解和使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
	"fmt"
	"net"
)

func main() {
	f, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: 8080,
	})
	if err != nil {
		panic(err)
	}
	defer f.Close()
	var data [2048]byte
	for {
		n, addr, err := f.ReadFromUDP(data[:])
		if err != nil {
			fmt.Printf("%#v\n", err)
			continue
		}
		//fmt.Printf("%#v, %#v, %#v\n", n, addr, err)
		fmt.Printf("msg := %s\n", data[:n])
		_, err = f.WriteToUDP([]byte("ok\n"), addr)
		if err != nil {
			fmt.Println("write to udp,err := ", err)
			continue
		}

	}

}

/*
PS D:\ASUS\Desktop> ncat localhost 8080 -u
hello world
hello world
hello worl

*/