UDP

Go

Echo client

The client resolves a UDP address and then creates a conection using net.DailUDP(). It reads and writes to the connection. It sets a timeout on each read using SetReadDeadline().

The code is EchoClient.go:


/* UDP EchoClient
 */
package main

import (
	"fmt"
	"net"
	"os"
	"runtime"
	"bufio"
	"time"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s host:port", os.Args[0])
		os.Exit(1)
	}
	service := os.Args[1]

	console :=  bufio.NewReader(os.Stdin)

	udpAddr, err := net.ResolveUDPAddr("udp", service)
	checkError(err)

	conn, err := net.DialUDP("udp", nil, udpAddr)
	checkError(err)

	eol_len := 1 // POSIX: \n
	if runtime.GOOS == "windows" {
		eol_len = 2 // Windows: \r\n
	}
	
	for {
		line, _ := console.ReadString('\n')
		fmt.Println("Line was " + line)
		if line[:len(line) - eol_len] == "BYE" {
			break
		}

		_, err = conn.Write([]byte(line))
		checkError(err)

		conn.SetReadDeadline(time.Now().Add(15 * time.Second))
		// see https://ops.tips/blog/udp-client-and-server-in-go/#receiving-from-a-udp-connection-

		var buf [512]byte
		n, err := conn.Read(buf[0:])
		if err != nil {
			fmt.Println("Error receiving data")
			continue;
		}
		fmt.Println("received: '" + string(buf[0:n]) + "'")
	}
	os.Exit(0)
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error ", err.Error())
		os.Exit(1)
	}
}

Echo server

Go listens on a UDP port, and then reads from and writes to the UDP conection. The code is EchoServer.go:


/* UDPEchoServer
 */
package main

import (
	"fmt"
	"net"
	"os"
)

func main() {

	service := ":2000"
	udpAddr, err := net.ResolveUDPAddr("udp", service)
	checkError(err)

	conn, err := net.ListenUDP("udp", udpAddr)
	checkError(err)

	for {
		handleClient(conn)
	}
}

func handleClient(conn *net.UDPConn) {

	var buf [512]byte

	nread, addr, err := conn.ReadFromUDP(buf[0:])
	if err != nil {
		return
	}
	fmt.Println("received: %d", nread)
	conn.WriteToUDP(buf[:nread], addr)
}

func checkError(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fatal error ", err.Error())
		os.Exit(1)
	}
}


Copyright © Jan Newmarch, jan@newmarch.name
Creative Commons License
" Network Programming using Java, Go, Python, Rust, JavaScript and Julia" by Jan Newmarch is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License .
Based on a work at https://jan.newmarch.name/NetworkProgramming/ .

If you like this book, please contribute using PayPal