UDP Protocol 介紹

Client side 程式

// init
    raddr, err := net.ResolveUDPAddr("udp", address)
    if err != nil {
        // handle error
    }
       
    conn, err := net.DialUDP("udp", nil, raddr)
    if err != nil {
        // handle error
    }
        ....... 
    // send message
    buffer := make([]byte, maxBufferSize)
    n, addr, err := conn.ReadFrom(buffer)
    if err != nil {
        // handle error
    }
         .......            
    // receive message
    buffer := make([]byte, maxBufferSize)
    n, err = conn.WriteTo(buffer[:n], addr)
    if err != nil {
        // handle error
    }

Server side

 // init
    udpAddr, err := net.ResolveUDPAddr(resolver, serverAddr)
    if err != nil {
        // handle error
    }
    
    conn, err := net.ListenUDP("udp", udpAddr)
    if err != nil {
        // handle error
    }
        .......
    // send message
    buffer := make([]byte, maxBufferSize)
    n, addr, err := conn.ReadFromUDP(buffer)
    if err != nil {
        // handle error
    }
         .......
    // receive message
    buffer := make([]byte, maxBufferSize)
    n, err = conn.WriteToUDP(buffer[:n], addr)
    if err != nil {
        // handle error
    }