| by suyi | No comments

Go:udp简单使用

编写server.go

 package main

 import (
         "fmt"
         "log"
         "net"
 )

 func handleUDPConnection(conn *net.UDPConn) {
         // 读取或写入
         buffer := make([]byte, 1024)
         n, addr, err := conn.ReadFromUDP(buffer)
         fmt.Println("UDP client : ", addr)
         fmt.Println("Received from UDP client :  ", string(buffer[:n]))
         if err != nil {
                 log.Fatal(err)
         }
         // 需要在WriteToUDP()函数中指定客户端地址
         message := []byte("Hello UDP client!")
         _, err = conn.WriteToUDP(message, addr)
         if err != nil {
                 log.Println(err)
         }
 }

 func main() {
         hostName := "localhost"
         portNum := "6000"
         service := hostName + ":" + portNum
         udpAddr, err := net.ResolveUDPAddr("udp4", service)
         if err != nil {
                 log.Fatal(err)
         }
         // 设置监听
         ln, err := net.ListenUDP("udp", udpAddr)
         if err != nil {
                 log.Fatal(err)
         }
         fmt.Println("UDP server up and listening on port 6000")
         defer ln.Close()
         for {
                 // 等待连接
                 handleUDPConnection(ln)
         }

 }

编写client.go

package main

 import (
         "log"
         "net"
         "fmt"
 )

 func main() {
         hostName := "localhost"
         portNum := "6000"
         service := hostName + ":" + portNum
         RemoteAddr, err := net.ResolveUDPAddr("udp", service)
         // LocalAddr := nil
         conn, err := net.DialUDP("udp", nil, RemoteAddr)
         if err != nil {
                 log.Fatal(err)
         }
         log.Printf("Established connection to %s \n", service)
         log.Printf("Remote UDP address : %s \n", conn.RemoteAddr().String())
         log.Printf("Local UDP client address : %s \n", conn.LocalAddr().String())
         defer conn.Close()
         message := []byte("Hello UDP server!")
         _, err = conn.Write(message)
         if err != nil {
                 log.Println(err)
         }
         buffer := make([]byte, 1024)
         n, addr, err := conn.ReadFromUDP(buffer)
         fmt.Println("UDP Server : ", addr)
         fmt.Println("Received from UDP server : ", string(buffer[:n]))

 }

分别运行server/client

UDP server up and listening on port 6000
UDP client : 127.0.0.1:63937
Received from UDP client : Hello UDP server!
2021/07/15 15:14:56 Established connection to localhost:6000
2021/07/15 15:14:56 Remote UDP address : 127.0.0.1:6000
2021/07/15 15:14:56 Local UDP client address : 127.0.0.1:63937
UDP Server : 127.0.0.1:6000
Received from UDP server : Hello UDP client!

发表评论