Created
April 11, 2024 15:09
-
-
Save dsiddharth/f295da206ecba2fbfef596c9274a16ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Run with ./server $PORT | |
import ( | |
"fmt" | |
"net" | |
"os" | |
) | |
func main() { | |
// Check for the correct number of arguments | |
if len(os.Args) != 2 { | |
fmt.Fprintf(os.Stderr, "Usage: %s <port>\n", os.Args[0]) | |
os.Exit(1) | |
} | |
// The port on which the server will listen for UDP packets | |
port := os.Args[1] | |
// Resolve the UDP address | |
addr, err := net.ResolveUDPAddr("udp", ":"+port) | |
if err != nil { | |
fmt.Println("Error resolving UDP address:", err) | |
os.Exit(1) | |
} | |
// Create a UDP socket and listen on the specified port | |
conn, err := net.ListenUDP("udp", addr) | |
if err != nil { | |
fmt.Println("Error listening on UDP port:", err) | |
os.Exit(1) | |
} | |
defer conn.Close() | |
fmt.Printf("UDP echo server listening on port %s\n", port) | |
// Buffer to store received data | |
buffer := make([]byte, 1024) | |
for { | |
// Read data from connection | |
n, clientAddr, err := conn.ReadFromUDP(buffer) | |
if err != nil { | |
fmt.Println("Error reading from UDP:", err) | |
continue | |
} | |
fmt.Printf("Received: %s from %s\n", string(buffer[:n]), clientAddr.String()) | |
// Echo data back to sender | |
_, err = conn.WriteToUDP(buffer[:n], clientAddr) | |
if err != nil { | |
fmt.Println("Error writing to UDP:", err) | |
continue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment