Developing a UDP server
This section shows how to develop a UDP server, which generates and returns random numbers to its clients. The code for the UDP server (udpS.go
) is as follows:
package main
import (
"fmt"
"math/rand"
"net"
"os"
"strconv"
"strings"
"time"
)
func random(min, max int) int {
return rand.Intn(max-min) + min
}
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide a port number!")
return
}
PORT := ":" + arguments[1]
The UDP port number the server is going to listen to is provided as a command-line argument.
s, err := net.ResolveUDPAddr("udp4", PORT)
if err != nil {
fmt.Println(err)
return
}
The net.ResolveUDPAddr()
function creates a UDP endpoint that is going to be used to create the server.
connection, err := net.ListenUDP...