broadcast

package
v1.2.5 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2026 License: MIT Imports: 5 Imported by: 0

README

UDP Broadcast Discovery

基于 UDP Broadcast 的局域网服务发现库。

协议约定:

  • 客户端向固定 UDP 端口广播 JSON 查询:{"type":"query","service":"service-x"}
  • 服务端收到后向请求来源单播 JSON 响应:{"type":"response","service":"service-x","addr":"IP:PORT"}

作为依赖使用

服务端:

package main

import (
	"context"
	"log"

	broadcastserver "github.com/omalloc/contrib/net/broadcast/server"
)

func main() {
	if err := broadcastserver.ListenAndServe(context.Background(), broadcastserver.Config{
		Service:     "service-x",
		ServicePort: 8080,
		Meta: map[string]string{
			"version": "1.0.0",
		},
		Logger: log.Default(),
	}); err != nil {
		log.Fatal(err)
	}
}

客户端:

package main

import (
	"context"
	"fmt"
	"log"

	broadcastclient "github.com/omalloc/contrib/net/broadcast/client"
)

func main() {
	results, err := broadcastclient.Discover(context.Background(), broadcastclient.Config{
		Service: "service-x",
		Logger:  log.Default(),
	})
	if err != nil {
		log.Fatal(err)
	}

	for _, result := range results {
		fmt.Println(result.Addr, result.Meta)
	}
}

Documentation

Index

Constants

View Source
const (
	MessageTypeQuery    = "query"
	MessageTypeResponse = "response"
)
View Source
const DefaultDiscoveryPort = 5353

Variables

This section is empty.

Functions

func AddrWithPort

func AddrWithPort(ip net.IP, port int) string

func EnableBroadcast

func EnableBroadcast(conn *net.UDPConn) error

func EncodeMessage

func EncodeMessage(msg Message) ([]byte, error)

func IPv4ForPeer

func IPv4ForPeer(peer net.IP) (net.IP, error)

func ParseIPv4

func ParseIPv4(addr *net.UDPAddr) net.IP

func SubnetBroadcastTargets

func SubnetBroadcastTargets(port int) ([]*net.UDPAddr, error)

Types

type Message

type Message struct {
	Type    string            `json:"type"`
	Service string            `json:"service"`
	Addr    string            `json:"addr,omitempty"`
	Meta    map[string]string `json:"meta,omitempty"`
}

func DecodeMessage

func DecodeMessage(data []byte) (Message, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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