course/networkProgram/UDP/udp_client.go

40 lines
628 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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]))
}
}