使用 Dispatch 分发源发送 UDP 广播消息并监听响应的框架。
我认为现代应用程序不应再使用此软件包。请查看 Apple 的 NWConnection
。
iOS 11+, Swift 5.0
包含一个示例应用程序,演示了 UDPBroadcastConnection 的功能。这个例子可能无法直接使用,因为你需要有人在你的网络上的正确 UDP 端口上监听和响应。
在端口 35602
上创建一个 UDPBroadcastConnection
,并使用一个闭包来处理响应。
broadcastConnection = try UDPBroadcastConnection(
port: 35602,
handler: { (response: (ipAddress: String, port: Int, response: [UInt8])) -> Void in
print("Received from \(response.ipAddress):\(response.port):\n\n\(response.response)")
},
errorHandler: { (error) in
print(error)
})
注意:确保保持对 broadcastConnection
的强引用(例如,将其存储在一个属性中),以便能够接收响应。
通过广播发送消息
try broadcastConnection.sendBroadcast("This is a test!")
你可以通过在你的 Mac 上运行包含的 receive_and_reply.py
脚本(已使用 Python 2.7.10 测试)来测试广播和用于接收消息的处理程序。如果你使用示例应用程序发送广播,你应该在终端中看到发送的消息,并在示例应用程序中看到脚本的回复。
将以下行添加到你的 Cartfile。
github "gunterhager/UDPBroadcastConnection"
然后运行 carthage update
。
只需将 UDPBroadcastConnection
文件夹中的 .swift
文件拖放到你的项目中即可。
UDPBroadcastConnection
在 MIT 许可证下可用。有关详细信息,请参见 LICENSE 文件。
用 ❤ 在 all about apps 制作。