I am looking for some examples on GCDAsyncUdpSocke

2019-04-12 06:34发布

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条回答
Fickle 薄情
2楼-- · 2019-04-12 06:55

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)
    }
}
查看更多
登录 后发表回答