eg:
client(客户端)
package main
import (
"bufio"
"fmt"
"net"
"os"
)
func main() {
socket ,err :=net.DialUDP("udp",nil,&net.UDPAddr{
IP: net.IPv4(127,0,0,1),
Port:40000,
})
if err != nil {
fmt.Println("连接服务器失败, err:", err)
return
}
var reply [1024]byte
defer socket.Close()
reader := bufio.NewReader(os.Stdin)
for{
fmt.Print("请输入内容:")
msg,_ := reader.ReadString('\n')
socket.Write([]byte(msg))
n,_,err := socket.ReadFromUDP(reply[:])
if err != nil{
fmt.Println("redv reply msg failed,err;",err)
return
}
fmt.Println("收到回复信息",string(reply[:n]))
}
}
server(服务端)
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 failed err:", err)
return
}
var data [1024]byte
for{
n,addr,err := conn.ReadFromUDP(data[:])
if err != nil {
fmt.Println("read from UDP failed err:", err)
return
}
fmt.Println(data[:n])
reply := strings.ToUpper(string(data[:n]))
conn.WriteToUDP([]byte(reply),addr)
}
}
|