create a udp server on a specific port in go

To create a UDP server on a specific port in Go, you can use the net package which provides support for various internet protocols. Here's an example code snippet that creates a UDP server listening on port 8080:

main.go
package main

import (
    "fmt"
    "net"
)

func main() {
    // Create a UDP connection on port 8080
    conn, err := net.ListenUDP("udp", &net.UDPAddr{
        IP:   net.IPv4(0, 0, 0, 0),
        Port: 8080,
        Zone: "",
    })
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    fmt.Printf("Server listening on %s\n", conn.LocalAddr().String())

    for {
        // Read incoming data
        buffer := make([]byte, 1024)
        n, addr, err := conn.ReadFromUDP(buffer)
        if err != nil {
            fmt.Printf("Error reading data: %s", err)
            continue
        }

        fmt.Printf("Received %d bytes from %s:%d\n", n, addr.IP.String(), addr.Port)

        // Echo incoming data back to client
        _, err = conn.WriteToUDP(buffer[:n], addr)
        if err != nil {
            fmt.Printf("Error sending data: %s", err)
            continue
        }
    }
}
912 chars
41 lines

In the above code, we first create a UDP connection using net.ListenUDP() and specify the protocol as "udp" and the port as 8080. We then use a defer statement to ensure that the connection is closed when the program exits.

We then loop indefinitely and read incoming data using conn.ReadFromUDP(). Once data is received, we print out the number of bytes received and the source address and port. We then echo the incoming data back to the client by writing it using conn.WriteToUDP().

related categories

gistlibby LogSnag