背景:Swift:使用GCDAsyncUdpSocket接收UDP
我希望能夠在iOS應用程序和服務器之間發送和接收UDP數據包。 服務器將每個傳入消息回顯給客戶端應用程序。 服務器已經過測試並確認正在工作。我有一個StartViewController,它啓動了兩個實現GCDAsyncUdpSocketDelegate的類,一個用於發送,另一個用於接收。 「發送套接字」正在工作,服務器收到消息。
問題:
的應用從未得到它發出後回傳入的消息。與偵聽套接字設置的東西可能是錯誤的,因爲didReceiveData永遠不會被調用。
我這樣做完全錯了嗎?
開始:
class StartViewController: UIViewController {
var inSocket : InSocket!
var outSocket : OutSocket!
override func viewDidLoad() {
super.viewDidLoad()
inSocket = InSocket()
outSocket = OutSocket()
}
@IBAction func goButton(sender: UIButton) {
outSocket.send("This is a message!")
}
}
接收:
class InSocket: NSObject, GCDAsyncUdpSocketDelegate {
let IP = "255.255.255.255"
let PORT:UInt16 = 5556
var socket:GCDAsyncUdpSocket!
override init(){
super.init()
setupConnection()
}
func setupConnection(){
var error : NSError?
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
socket.bindToPort(PORT, error: &error)
socket.enableBroadcast(true, error: &error)
socket.joinMulticastGroup(IP, error: &error)
socket.beginReceiving(&error)
}
func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
println("incoming message: \(data)");
}
}
發送:
class OutSocket: NSObject, GCDAsyncUdpSocketDelegate {
let IP = "90.112.76.180"
let PORT:UInt16 = 5556
var socket:GCDAsyncUdpSocket!
override init(){
super.init()
setupConnection()
}
func setupConnection(){
var error : NSError?
socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
socket.connectToHost(IP, onPort: PORT, error: &error)
}
func send(message:String){
let data = message.dataUsingEncoding(NSUTF8StringEncoding)
socket.sendData(data, withTimeout: 2, tag: 0)
}
func udpSocket(sock: GCDAsyncUdpSocket!, didConnectToAddress address: NSData!) {
println("didConnectToAddress");
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotConnect error: NSError!) {
println("didNotConnect \(error)")
}
func udpSocket(sock: GCDAsyncUdpSocket!, didSendDataWithTag tag: Int) {
println("didSendDataWithTag")
}
func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) {
println("didNotSendDataWithTag")
}
}
編輯: 新增遺忘代碼行。
確切位置在哪裏,你在初始化你InSocket插座財產。建立連接? – Anton 2014-11-06 22:11:48
安東。 Thx的注意。這是我的項目代碼複製/粘貼錯誤,我剛剛添加它。這不是問題,因爲我的項目代碼中有socket初始化。 – rilar 2014-11-07 07:12:44