35 lines
615 B
Go
35 lines
615 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"net"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// UDP sever
|
||
|
func main() {
|
||
|
conn, err := net.ListenUDP("udp", &net.UDPAddr{
|
||
|
IP: net.IPv4(127, 0, 0, 1),
|
||
|
Port: 40000,
|
||
|
})
|
||
|
if err != nil {
|
||
|
log.Fatal("listen udp failed:", err)
|
||
|
return
|
||
|
}
|
||
|
defer conn.Close()
|
||
|
//不需要建立链接,直接收发数据
|
||
|
data := make([]byte, 1024)
|
||
|
for {
|
||
|
n, addr, err := conn.ReadFromUDP(data)
|
||
|
if err != nil {
|
||
|
log.Println("read from udp failed:", err)
|
||
|
}
|
||
|
fmt.Printf("%s\n", data[:n])
|
||
|
reply := string(data[:n])
|
||
|
reply = strings.ToUpper(reply)
|
||
|
//发送数据
|
||
|
conn.WriteToUDP([]byte(reply), addr)
|
||
|
}
|
||
|
}
|