I am looking for some examples on GCDAsyncUdpSocket, but found none that works

馋奶兔 提交于 2019-12-05 03:13:46

问题


didReceiveData was never called - I coded this swift class which was called by my mainline UIViewController to send out a message to the server which received it OK, but when the server sent a response back, the client never receives it because the didReceiveData() was never triggered.

I kept googling and look at the doc, and it said that the client does NOT need to bind (Only the server needs doing this) Can anyone help me with this - Thanks in advance.

import UIKit

import CocoaAsyncSocket


class UdpSocketSR: NSObject, GCDAsyncUdpSocketDelegate {


var socket:GCDAsyncUdpSocket!

var rc : Int = 0
var messageOut : String = ""
var messageIn : String = ""


override init(){
    super.init()
}


func SetupAndSend(IP: String, PORT: Int, DATA : String) -> Int
{
    socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)


    messageOut = DATA
    do {
        let data = messageOut.data(using: String.Encoding.utf8)

        socket.send(data!, toHost: IP, port: UInt16(PORT), withTimeout: 3, tag: 0)

        try socket.beginReceiving()
        sleep(3)
        socket.close()

    } catch {
        rc = -1
    }

    return rc
}



private func udpSocket(sock:GCDAsyncUdpSocket!,didConnectToAddress data : NSData!){
     rc = -2
}

private func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData dataRecv: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {

    messageIn = NSString(data: dataRecv as Data, encoding: String.Encoding.utf8.rawValue) as! String

} 


}

回答1:


Why you close your socket after send? It works for me with the bind.

class UdpSocketSR: GCDAsyncSocket, GCDAsyncUdpSocketDelegate {
    var socket: GCDAsyncUdpSocket!

    func SetupAndSend() {
       let host = "127.0.0.1" // IP
       let port: UInt16 = 1234   // Port
       let message = messageOut.data(using: String.Encoding.utf8)!

       socket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main)

       do {
           try socket.bindToPort(port)
           try socket.enableBroadcast(true)
           try socket.beginReceiving()
           socket.send(message, toHost: host, port: port, withTimeout: 2, tag: 0)
       }
    }

   // Delegate
   func udpSocket(_ sock: GCDAsyncUdpSocket, didNotConnect error: Error){
      print("UDP Connection error: \(error)")
   }

   func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
        var host: NSString?
        var port: UInt16 = 0
        GCDAsyncUdpSocket.getHost(&host, port: &port, fromAddress: address)
        print(host)
    }
}


来源:https://stackoverflow.com/questions/42547555/i-am-looking-for-some-examples-on-gcdasyncudpsocket-but-found-none-that-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!