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 ¶
- type Client
- func (c *Client) Close() error
- func (c *Client) Connect(network, address string) error
- func (c *Client) GetLocalAddr() net.Addr
- func (c *Client) GetRemoteAddr() net.Addr
- func (c *Client) Receive(bufferSize int, timeout time.Duration) ([]byte, net.Addr, error)
- func (c *Client) Send(data []byte) (int, error)
- func (c *Client) SendTo(data []byte, address string) (int, error)
- func (c *Client) SetReadBuffer(bytes int) error
- func (c *Client) SetWriteBuffer(bytes int) error
- type ErrorHandler
- type PacketHandler
- type Server
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 ¶
Close closes the UDP connection.
Returns ¶
- error: Error if close fails, nil on success
Examples ¶
err := client.Close()
func (*Client) Connect ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
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)
}