udp

package
v1.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 1, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

README

UDP Socket Package

Package providing UDP socket client and server implementation for Go.

Features

  • UDP Socket Client: Packet send and receive operations
  • UDP Socket Server: Processing through packet handlers
  • Concurrency Support: Asynchronous handler option
  • Timeout Support: Receive timeout setting
  • Error Handling: Optional error handler
  • Buffer Management: Read/write buffer size settings

Installation

go get github.com/common-library/go/socket/udp

UDP Characteristics

UDP (User Datagram Protocol) is a connectionless protocol:

  • No packet delivery guarantee (packets may be lost)
  • No order guarantee (packets may not arrive in order)
  • No duplication prevention (same packet may arrive multiple times)
  • Low overhead and fast transmission speed
  • Suitable for real-time applications (streaming, gaming, DNS, etc.)

Usage Examples

UDP Client
Basic Usage
package main

import (
    "fmt"
    "log"
    "time"
    "github.com/common-library/go/socket/udp"
)

func main() {
    client := &udp.Client{}
    
    // Connect to server
    err := client.Connect("udp4", "localhost:8080")
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()
    
    // Send data
    data := []byte("Hello, UDP Server!")
    n, err := client.Send(data)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Sent %d bytes\n", n)
    
    // Receive data (5 second timeout)
    received, addr, err := client.Receive(1024, 5*time.Second)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Received from %s: %s\n", addr, received)
}
Send to Different Address (SendTo)
client := &udp.Client{}
client.Connect("udp4", "localhost:8080")
defer client.Close()

// Send to different address than Connect
n, err := client.SendTo([]byte("Hello"), "192.168.1.100:9000")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Sent %d bytes to different address\n", n)
Buffer Size Settings
client := &udp.Client{}
client.Connect("udp4", "localhost:8080")
defer client.Close()

// Set read/write buffer sizes
client.SetReadBuffer(65536)   // 64KB
client.SetWriteBuffer(65536)  // 64KB
UDP Server
Basic Echo Server
package main

import (
    "fmt"
    "log"
    "net"
    "os"
    "os/signal"
    "syscall"
    "github.com/common-library/go/socket/udp"
)

func main() {
    server := &udp.Server{}
    
    // Start echo server
    err := server.Start("udp4", ":8080", 1024,
        func(data []byte, addr net.Addr, conn net.PacketConn) {
            fmt.Printf("Received from %s: %s\n", addr, data)
            // Echo back
            conn.WriteTo(data, addr)
        },
        false,  // Synchronous processing
        nil,    // No error handler
    )
    if err != nil {
        log.Fatal(err)
    }
    defer server.Stop()
    
    fmt.Printf("Server listening on %s\n", server.GetLocalAddr())
    
    // Wait for signal
    sigChan := make(chan os.Signal, 1)
    signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
    <-sigChan
    
    fmt.Println("Shutting down...")
}
Asynchronous Handler with Error Processing
server := &udp.Server{}

err := server.Start("udp4", ":8080", 1024,
    // Packet handler
    func(data []byte, addr net.Addr, conn net.PacketConn) {
        // Process each packet in a separate goroutine
        processPacket(data, addr)
        
        // Send response
        response := []byte("Acknowledged")
        conn.WriteTo(response, addr)
    },
    true,  // Asynchronous processing (use goroutines)
    // Error handler
    func(err error) {
        log.Printf("Read error: %v", err)
    },
)
if err != nil {
    log.Fatal(err)
}
defer server.Stop()
Multicast Server Example
package main

import (
    "fmt"
    "log"
    "net"
    "github.com/common-library/go/socket/udp"
)

func main() {
    // Multicast address
    multicastAddr := "224.0.0.1:9999"
    
    server := &udp.Server{}
    
    err := server.Start("udp4", multicastAddr, 1024,
        func(data []byte, addr net.Addr, conn net.PacketConn) {
            fmt.Printf("Multicast from %s: %s\n", addr, data)
        },
        true,
        func(err error) {
            log.Printf("Error: %v", err)
        },
    )
    if err != nil {
        log.Fatal(err)
    }
    defer server.Stop()
    
    select {} // Keep running
}
Status Check
server := &udp.Server{}
server.Start("udp4", ":8080", 1024, handler, false, nil)

// Check server running status
if server.IsRunning() {
    fmt.Println("Server is running")
    fmt.Printf("Listening on: %s\n", server.GetLocalAddr())
}

// Stop server
server.Stop()

if !server.IsRunning() {
    fmt.Println("Server stopped")
}

API Documentation

Client
Connect(network, address string) error

Creates a UDP connection.

  • network: Network type ("udp", "udp4", "udp6")
  • address: Remote address (e.g., "localhost:8080")
Send(data []byte) (int, error)

Sends data to the connected address.

  • data: Byte array to send
  • return: Number of bytes sent, error
SendTo(data []byte, address string) (int, error)

Sends data to a specific address.

  • data: Byte array to send
  • address: Destination address
  • return: Number of bytes sent, error

Note: Creates a temporary socket for each call, which may cause performance degradation with frequent use.

Receive(bufferSize int, timeout time.Duration) ([]byte, net.Addr, error)

Receives data.

  • bufferSize: Maximum number of bytes to read
  • timeout: Read timeout (no timeout if 0)
  • return: Received data, sender address, error
Close() error

Closes the UDP connection.

GetLocalAddr() net.Addr

Returns the local network address.

GetRemoteAddr() net.Addr

Returns the remote network address.

SetReadBuffer(bytes int) error

Sets the OS receive buffer size.

SetWriteBuffer(bytes int) error

Sets the OS send buffer size.

Server
Start(network, address string, bufferSize int, handler PacketHandler, asyncHandler bool, errorHandler ErrorHandler) error

Starts the UDP server.

  • network: Network type ("udp", "udp4", "udp6")
  • address: Bind address (e.g., ":8080", "0.0.0.0:8080")
  • bufferSize: Maximum size of received packets (bytes)
  • handler: Packet processing function
  • asyncHandler: If true, each handler runs in a goroutine
  • errorHandler: Read error processing function (can be nil)
Stop() error

Stops the UDP server. Waits until all running handlers are complete.

IsRunning() bool

Returns the server running status.

  • return: true if server is running
GetLocalAddr() net.Addr

Returns the local address the server is listening on.

Type Definitions

PacketHandler
type PacketHandler func(data []byte, addr net.Addr, conn net.PacketConn)

Function type that processes received UDP packets.

ErrorHandler
type ErrorHandler func(err error)

Function type that handles errors occurring during packet reception.

Notes

  • UDP does not guarantee packet delivery, order, or duplication prevention
  • For critical data, implement acknowledgment and retransmission mechanisms at the application level
  • Packets exceeding network MTU may be fragmented or lost
Client
  • Send() and Receive() must be used after calling Connect()
  • SendTo() creates a temporary socket, so be mindful of performance
  • If timeout occurs, an i/o timeout error is returned
Server
  • When asyncHandler=true, handlers run concurrently, so concurrency must be considered
  • When asyncHandler=false, if handlers take a long time, next packet reception will be delayed
  • Stop() blocks until all handlers are complete
  • Use error handler for logging or monitoring network errors

Performance Tips

  1. Buffer size: Set buffer according to expected maximum packet size
  2. Asynchronous processing: Use asyncHandler=true in high-load environments
  3. OS buffers: Utilize SetReadBuffer()/SetWriteBuffer() for handling large volumes of packets
  4. Timeout: Set appropriate timeout to prevent infinite waiting

License

This package follows the project's license.

Documentation

Overview

Package udp provides UDP socket client and server implementations.

This package simplifies UDP network programming with packet-oriented communication. UDP is connectionless and does not guarantee delivery, ordering, or duplicate protection.

Features

  • UDP socket client
  • UDP socket server with packet handler
  • Packet send and receive operations
  • Concurrent packet processing (server)
  • Timeout support
  • Broadcast and multicast support
  • Local and remote address access

Basic Client Example

client := &udp.Client{}
err := client.Connect("udp4", "localhost:8080")
client.Send([]byte("Hello"))
data, addr, _ := client.Receive(1024, 5*time.Second)
client.Close()

UDP Server Example

server := &udp.Server{}
err := server.Start("udp4", ":8080", 1024,
    func(data []byte, addr net.Addr, conn net.PacketConn) {
        fmt.Printf("Received from %s: %s\n", addr, data)
        conn.WriteTo(data, addr)  // Echo back
    },
    true,  // Async handler
    nil,   // No error handler
)
defer server.Stop()

Package udp provides UDP socket server and client implementations.

This package simplifies UDP network programming with packet-oriented communication. UDP is connectionless and does not guarantee delivery, ordering, or duplicate protection.

Features

  • UDP socket server with packet handler
  • UDP socket client
  • Concurrent packet processing
  • Graceful shutdown support
  • Timeout support

Basic Server Example

server := &udp.Server{}
err := server.Start("udp4", ":8080", 1024, func(data []byte, addr net.Addr, conn net.PacketConn) {
    fmt.Printf("Received from %s: %s\n", addr, data)
    conn.WriteTo(data, addr)  // Echo back
}, true, nil)
defer server.Stop()

Basic Client Example

client := &udp.Client{}
err := client.Connect("udp4", "localhost:8080")
client.Send([]byte("Hello"))
data, addr, _ := client.Receive(1024, 5*time.Second)
client.Close()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a struct that provides UDP client related methods.

func (*Client) Close

func (c *Client) Close() error

Close closes the UDP connection.

Returns

  • error: Error if close fails, nil on success

Examples

err := client.Close()

func (*Client) Connect

func (c *Client) Connect(network, address string) error

Connect creates a UDP connection with specific network type.

Parameters

  • network: Network type ("udp", "udp4", "udp6")
  • address: Remote address (e.g., "localhost:8080")

Returns

  • error: Error if connection fails, nil on success

Examples

client := &udp.Client{}
err := client.Connect("udp4", "localhost:8080")

func (*Client) GetLocalAddr

func (c *Client) GetLocalAddr() net.Addr

GetLocalAddr returns the local network address.

Returns

  • net.Addr: Local address, or nil if not connected

Examples

addr := client.GetLocalAddr()
if addr != nil {
    fmt.Println(addr.String())
}

func (*Client) GetRemoteAddr

func (c *Client) GetRemoteAddr() net.Addr

GetRemoteAddr returns the remote network address.

Returns

  • net.Addr: Remote address, or nil if not connected

Examples

addr := client.GetRemoteAddr()
if addr != nil {
    fmt.Println(addr.String())
}

func (*Client) Receive

func (c *Client) Receive(bufferSize int, timeout time.Duration) ([]byte, net.Addr, error)

Receive receives data from any source.

Parameters

  • bufferSize: Maximum bytes to read
  • timeout: Read timeout duration (0 for no timeout)

Returns

  • []byte: Received data
  • net.Addr: Source address
  • error: Error if receive fails, nil on success

Examples

data, addr, err := client.Receive(1024, 5*time.Second)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Received from %s: %s\n", addr, data)

func (*Client) Send

func (c *Client) Send(data []byte) (int, error)

Send sends data to the remote address.

Parameters

  • data: Byte array to send

Returns

  • int: Number of bytes sent
  • error: Error if send fails, nil on success

Examples

n, err := client.Send([]byte("Hello, Server!"))

func (*Client) SendTo

func (c *Client) SendTo(data []byte, address string) (int, error)

SendTo sends data to a specific address.

This method allows sending to a different address than the one specified in Connect(). For connected UDP sockets (using net.DialUDP), this creates a temporary unconnected socket for the send operation, which incurs some overhead. If you need to send to multiple different addresses frequently, consider using net.ListenPacket directly instead of Client.

Parameters

  • data: Byte array to send
  • address: Target address (can differ from Connect address)

Returns

  • int: Number of bytes sent
  • error: Error if send fails, nil on success

Examples

// Send to a different address than Connect
client.Connect("udp4", "localhost:8080")
n, err := client.SendTo([]byte("Hello"), "192.168.1.100:9000")

Performance Note

WARNING: Each SendTo() call creates and closes a temporary socket, which has significant performance overhead. For high-performance scenarios with multiple destinations, use net.ListenPacket directly:

conn, _ := net.ListenPacket("udp", ":0")
defer conn.Close()
conn.WriteTo(data1, addr1)
conn.WriteTo(data2, addr2)  // No temporary socket created

func (*Client) SetReadBuffer

func (c *Client) SetReadBuffer(bytes int) error

SetReadBuffer sets the size of the operating system's receive buffer.

Parameters

  • bytes: Buffer size in bytes

Returns

  • error: Error if setting fails, nil on success

func (*Client) SetWriteBuffer

func (c *Client) SetWriteBuffer(bytes int) error

SetWriteBuffer sets the size of the operating system's transmit buffer.

Parameters

  • bytes: Buffer size in bytes

Returns

  • error: Error if setting fails, nil on success

type ErrorHandler

type ErrorHandler func(err error)

ErrorHandler is a function type for handling errors during packet reception. It receives the error that occurred during ReadFrom operation.

type PacketHandler

type PacketHandler func(data []byte, addr net.Addr, conn net.PacketConn)

PacketHandler is a function type for handling received UDP packets. It receives the packet data, source address, and the packet connection. Handlers can use the connection to send responses back to the source.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is a struct that provides UDP server functionality. It handles incoming UDP packets and processes them using a PacketHandler.

func (*Server) GetLocalAddr

func (s *Server) GetLocalAddr() net.Addr

GetLocalAddr returns the local network address the server is listening on.

Returns

  • net.Addr: Local address, or nil if server is not started

Examples

addr := server.GetLocalAddr()
if addr != nil {
    fmt.Printf("Server listening on %s\n", addr)
}

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning returns whether the server is currently running.

Returns

  • bool: true if server is running, false otherwise

Examples

if server.IsRunning() {
    fmt.Println("Server is running")
}

func (*Server) Start

func (s *Server) Start(network, address string, bufferSize int, handler PacketHandler, asyncHandler bool, errorHandler ErrorHandler) error

Start starts the UDP server and begins listening for packets.

The server runs in a goroutine and calls the handler for each received packet. The handler is responsible for processing the packet and can send responses using the provided PacketConn.

Parameters

  • network: Network type ("udp", "udp4", "udp6")
  • address: Local address to bind (e.g., ":8080", "0.0.0.0:8080")
  • bufferSize: Maximum size for received packets in bytes
  • handler: Function to handle received packets
  • asyncHandler: If true, each packet handler runs in a separate goroutine, enabling concurrent packet processing. If false, packets are processed sequentially which may cause receive delays if handlers are slow.
  • errorHandler: Optional function to handle read errors (can be nil)

Returns

  • error: Error if server fails to start, nil on success

Examples

server := &udp.Server{}
err := server.Start("udp4", ":8080", 1024,
    func(data []byte, addr net.Addr, conn net.PacketConn) {
        log.Printf("Received %d bytes from %s\n", len(data), addr)
        conn.WriteTo(data, addr)  // Echo server
    },
    true,  // Run handlers concurrently
    func(err error) {
        log.Printf("Read error: %v\n", err)
    },
)

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the UDP server and closes the connection.

This method signals the server goroutine to stop and closes the underlying packet connection. It waits for all running handlers to complete before returning. It is safe to call Stop multiple times.

Returns

  • error: Error if close fails, nil on success

Examples

err := server.Stop()
if err != nil {
    log.Printf("Error stopping server: %v", err)
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL