40 lines
628 B
Go
40 lines
628 B
Go
package main
|
||
|
||
import (
|
||
"bufio"
|
||
"fmt"
|
||
"log"
|
||
"net"
|
||
"os"
|
||
)
|
||
|
||
//UDP client
|
||
|
||
func main() {
|
||
socket, err := net.DialUDP("udp", nil, &net.UDPAddr{
|
||
IP: net.IPv4(127, 0, 0, 1),
|
||
Port: 40000,
|
||
})
|
||
if err != nil {
|
||
log.Fatal("连接服务端失败,err", err)
|
||
return
|
||
}
|
||
defer socket.Close()
|
||
reader := bufio.NewReader(os.Stdin)
|
||
reply := make([]byte, 512)
|
||
for {
|
||
fmt.Print("> ")
|
||
msg, _ := reader.ReadString('\n')
|
||
socket.Write([]byte(msg))
|
||
//收回复的数据
|
||
n, _, err := socket.ReadFromUDP(reply)
|
||
if err != nil {
|
||
fmt.Println("read reply msg failed:", err)
|
||
return
|
||
}
|
||
fmt.Print(string(reply[:n]))
|
||
|
||
}
|
||
|
||
}
|