[英]Swift - UDP Receive & Send
我正在嘗試在 iPhone 應用程序和 ESP8266 之間發送和接收 UDP 數據包。 我有幾個 ESP 設備都可以正常通信,但是我一生都無法為 iOS 創建任何可以查看或發送任何內容的內容。 我嘗試過 SwiftSocket、CocoaAsyncSocket、UDPBroadcastConnection、Apple 的新 NetworkExtension/NetworkConnection 庫,但都無濟於事。
目標設備IP地址是192.168.4.1,我們使用的端口是4210。目標設備在255.255.255.255上發送廣播。 我可以從我的 macbook 上看到這些。
嘗試從我的應用程序向任何 IP 發送或接收數據包均未成功。 我曾嘗試使用 mac 應用商店中的應用 PacketSender 對其進行測試。 誰能推薦一個解決方案的實際功能工作示例? 在這一點上,我不在乎使用上述哪個庫,我只需要移動一些數據。
我確保的一個步驟是:Xcode 中的應用程序啟用了網絡擴展功能。
這是我的 UDPBroadcastConnection 嘗試中的一個示例:
// in viewDidLoad()...
// ...
//broadcastConnection declared globally
broadcastConnection = UDPBroadcastConnection(port: 4210, handler: { (ip, port, response) in
print("Received from \(ip):\(port):\n\n\(response)")
})
這里沒有發送或接收任何內容。 使用網絡連接:
connection = NWConnection(host: "192.168.4.1", port: 4210, using: .udp)
connection!.stateUpdateHandler = { (newState) in
switch (newState) {
case .ready:
print("ready")
case .setup:
print("setup")
case .cancelled:
print("cancelled")
case .preparing:
print("Preparing")
default:
print("waiting or failed")
break
}
}
connection!.start(queue: .global())
connection!.receiveMessage { (data, context, isComplete, error) in
print("Got it")
print(data)
}
永遠不會收到任何東西。 然而,是否從准備狀態進入就緒狀態。 運行接收消息行,不打印任何內容。 從不打印有關狀態的任何進一步信息。 試圖通過按鈕操作運行接收消息嘗試多次,但似乎仍然不想接收。
可能值得注意的是,應用程序在模擬器上運行時能夠接收自己的發送,但似乎沒有任何設備外的連接(例如到/來自 PacketSender)
import UIKit
import Network
class ViewController: UIViewController {
var connection: NWConnection?
var hostUDP: NWEndpoint.Host = "192.168.4.1"
var portUDP: NWEndpoint.Port = 4210
@IBOutlet weak var lableRedy: UILabel!
@IBOutlet weak var lableReceive: UILabel!
@IBOutlet weak var lableMessege: UILabel!
override func viewDidLoad() {
}
//MARK:- UDP
func connectToUDP(_ hostUDP: NWEndpoint.Host, _ portUDP: NWEndpoint.Port) {
// Transmited message:
let messageToUDP = "7773010509060602040701000001010d0a"
self.connection = NWConnection(host: hostUDP, port: portUDP, using: .udp)
self.connection?.stateUpdateHandler = { (newState) in
print("This is stateUpdateHandler:")
switch (newState) {
case .ready:
print("State: Ready\n")
self.sendUDP(messageToUDP)
self.receiveUDP()
case .setup:
print("State: Setup\n")
case .cancelled:
print("State: Cancelled\n")
case .preparing:
print("State: Preparing\n")
default:
print("ERROR! State not defined!\n")
}
}
self.connection?.start(queue: .global())
}
func sendUDP(_ content: Data) {
self.connection?.send(content: content, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
if (NWError == nil) {
print("Data was sent to UDP")
} else {
print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
}
})))
}
func sendUDP(_ content: String) {
let contentToSendUDP = content.data(using: String.Encoding.utf8)
self.connection?.send(content: contentToSendUDP, completion: NWConnection.SendCompletion.contentProcessed(({ (NWError) in
if (NWError == nil) {
print("Data was sent to UDP")
DispatchQueue.main.async { self.lableRedy.text = "Data was sent to UDP" }
} else {
print("ERROR! Error when data (Type: Data) sending. NWError: \n \(NWError!)")
}
})))
}
func receiveUDP() {
self.connection?.receiveMessage { (data, context, isComplete, error) in
if (isComplete) {
print("Receive is complete")
DispatchQueue.main.async { self.lableReceive.text = "Receive is complete" }
if (data != nil) {
let backToString = String(decoding: data!, as: UTF8.self)
print("Received message: \(backToString)")
DispatchQueue.main.async { self.lableMessege.text = backToString }
} else {
print("Data == nil")
}
}
}
}
@IBAction func tappedSend(_ sender: Any) {
connectToUDP(hostUDP,portUDP)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.