40 lines
809 B
Go
40 lines
809 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
)
|
|
|
|
func main() {
|
|
// 1. 连接服务器
|
|
conn, err := net.Dial("udp", "localhost:9999")
|
|
if err != nil {
|
|
fmt.Println("Error connecting:", err)
|
|
return
|
|
}
|
|
defer conn.Close()
|
|
fmt.Println("Connected to server")
|
|
|
|
// 2. 发送数据
|
|
_, err = conn.Write([]byte("Hello, Server! I am a client."))
|
|
if err != nil {
|
|
fmt.Println("Error writing data:", err)
|
|
return
|
|
}
|
|
fmt.Println("Written 22 bytes:", "Hello, Server! I am a client.")
|
|
|
|
// 3. 接收数据
|
|
buf := make([]byte, 1500)
|
|
n, err := conn.Read(buf)
|
|
if err == io.EOF {
|
|
fmt.Println("Server closed connection")
|
|
return
|
|
}
|
|
if err != nil {
|
|
fmt.Println("Error reading data:", err)
|
|
return
|
|
}
|
|
fmt.Println("Read", len(buf), "bytes:", "Hello, Server! I have received your message: "+string(buf[:n])+"\n")
|
|
}
|