...

/

Developing a UDP Server

Developing a UDP Server

Let’s learn how to develop a UDP server with Go.

We'll cover the following...

This lesson shows us how to develop a UDP server, which generates and returns random numbers to its clients.

Coding example

The code for the UDP server (udpS.go) is as follows:

Press + to interact
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.

Press + to interact
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.

Press + to interact
connection, err := net.ListenUDP("udp4", s)
if err != nil {
fmt.Println(err)
return
}

The ...