zeroconf.*

类型
版本 版本 2024.3703
关键词 ZeroConf,网络
平台 Android、iOS、macOS、Windows、tvOS

概述

此插件允许您在局域网中发现和发布服务。它允许跨平台实现零配置基于 组播 DNS (mDNS) 的系统,可用于本地多人游戏或通过 WiFi 同步数据。

注意
  • 除 Windows 外,所有平台默认都支持服务发现。要在 Windows 上使用此插件,必须安装 Bonjour 3 或更高版本。

  • 您可以使用“Bonjour 浏览器”之类的软件来验证服务发现是否正常运行。

语法

local zeroconf = require( "plugin.zeroconf" )

函数

初始化

zeroconf.init()

服务发布

zeroconf.publish()

zeroconf.unpublish()

zeroconf.unpublishAll()

服务发现

zeroconf.browse()

zeroconf.stopBrowse()

zeroconf.stopBrowseAll()

事件

PluginZeroConfEvent

项目设置

要使用此插件,请在 `build.settings` 的 `plugins` 表中添加一个条目。添加后,构建服务器将在构建阶段集成该插件。

settings =
{
    plugins =
    {
        ["plugin.zeroconf"] =
        {
            publisherId = "com.coronalabs"
        },
    },
}

示例

-- Publishes a service of type '_corona_test._tcp' and then starts discovery for the service

-- Require the plugin
local zeroconf = require( "plugin.zeroconf" )

-- Listener to be called for ZeroConf events
local function zeroconfListener( event )

    -- Service has been found
    if ( event.phase == "found" and not event.isError ) then

        print( "SERVICE FOUND" )
        print( "-------------" )

        if event.serviceName then
            print( "Service name: " .. event.serviceName )
        end

        if event.port then
            print( "Port: " .. tostring(event.port) )
        end

        if ( event.addresses and #event.addresses > 0 ) then
            print( "Service provider addresses:" )
            for i = 1,#event.addresses do
                print( "  " .. event.addresses[i] )
            end
        end

    -- Service has been lost!
    elseif event.phase == "lost" then

        print( "SERVICE LOST!" )
        print( "-------------" )

        if event.serviceName then
            print( "Service name: " .. event.serviceName )
        end
    end
end

-- Initialize listener
zeroconf.init( zeroconfListener )

-- Generate a service name
local serviceName = system.getInfo("name") .. " (" .. system.getInfo("platformName") .. ")"

-- Publish a service (make it discoverable over the network)
local service = zeroconf.publish( { port=2929, name=serviceName, type="_corona_test._tcp" } )

-- Start looking for published services
local browser = zeroconf.browse( { type="_corona_test._tcp" } )