我正在寻找GCDAsyncUdpSocket的一些例子,但发现没有一个可行

时间:2017-03-02 05:31:49

标签: ios swift cocoaasyncsocket

从未调用

didReceiveData - 我编写了这个由我的主线 UIViewController 调用的swift类,以便向接收它的服务器发送消息,但是当服务器发回响应,客户端永远不会收到它,因为didReceiveData()从未被触发过。

我一直在谷歌搜索并查看文档,它说客户端不需要绑定(只有服务器需要这样做)任何人都可以帮助我 - 提前谢谢。

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 个答案:

答案 0 :(得分:2)

发送后为什么要关闭套接字?它适用于绑定。

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)
    }
}