udp编程
server
package main
import (
"fmt"
"net"
)
func main() {
listener, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.IPv4(0, 0, 0, 0),
Port: 30000,
})
if err != nil {
fmt.Println("启动server失败,err", err)
return
}
defer listener.Close()
for {
var buf [1024]byte
n, addr, err := listener.ReadFromUDP(buf[:])
if err != nil {
fmt.Println("接受消息失败:err:", err)
return
}
fmt.Printf("接受到来自%v的消息%v\n", addr, string(buf[:n]))
n, err = listener.WriteTo([]byte("今晚来我房间"), addr)
if err != nil{
return
}
}
}
client
package main
import (
"fmt"
"net"
)
func main() {
conn, err := net.Dial("udp", "127.0.0.1:30000")
if err != nil {
fmt.Println("连接server失败,err", err)
return
}
defer conn.Close()
n, err := conn.Write([]byte("今晚约么"))
if err != nil {
fmt.Println("发送消息失败: err", err)
return
}
var buf = make([]byte, 1024)
n, err = conn.Read(buf)
if err != nil {
fmt.Println("读取消息失败:err", err)
return
}
fmt.Println(string(buf[:n]))
}