客户端的设计,流程跟TCP客户端,几乎一样的流程
TCP客户端设计 https://blog.csdn.net/qq_22056419/article/details/88938633
1、拨号服务器
//第一步:拨号服务器
conn, err := net.Dial("udp", "127.0.0.1:8090")
if err != nil{
fmt.Println("拨号错误:", err)
return
}
2、循环向服务器发送,读取数据
//第二步:循环向服务器发送&接收消息
reader := bufio.NewReader(os.Stdin)
bytes := make([]byte, 1024)
for{
fmt.Print("请输入消息内容:")
msg, _, _ := reader.ReadLine()
//向服务器发送数据
conn.Write(msg)
//接收来自服务器的数据
fmt.Print("服务器回馈消息:")
size, _ := conn.Read(bytes)
fmt.Println(string(bytes[:size]))
}
下面是全部的代码
/*作者:itruirui@outlook.com*/
package main
import (
"fmt"
"net"
"os"
"bufio"
)
func main(){
//第一步:拨号服务器
conn, err := net.Dial("udp", "127.0.0.1:8090")
if err != nil{
fmt.Println("拨号错误:", err)
return
}
//第二步:循环向服务器发送&接收消息
reader := bufio.NewReader(os.Stdin)
bytes := make([]byte, 1024)
for{
fmt.Print("请输入消息内容:")
msg, _, _ := reader.ReadLine()
//向服务器发送数据
conn.Write(msg)
//接收来自服务器的数据
fmt.Print("服务器回馈消息:")
size, _ := conn.Read(bytes)
fmt.Println(string(bytes[:size]))
}
}