美文网首页
CocoaAsyncSocket使用(Swift4)

CocoaAsyncSocket使用(Swift4)

作者: 稀客花千树 | 来源:发表于2018-10-15 11:13 被阅读0次

CocoaAsyncSocket Github: https://github.com/robbiehanson/CocoaAsyncSocket

import UIKit

import CocoaAsyncSocket

protocol mySocketDelegate {

    func mySocketData(data:[UInt8],tag:Int)

}

public class MySocket:NSObject{

    var mSocket:GCDAsyncUdpSocket!

    let home_port :UInt16=1

    let Home_ip :String="255.255.255.255"

    let home_timeout :TimeInterval=2

    var delegate:mySocketDelegate?

    var socketTag :Int=0

    override public init() {

        super.init()

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

        do{

            try self.mSocket.enableBroadcast(true)

            try self.mSocket.bind(toPort:home_port)

            try self.mSocket.beginReceiving()

        }catch{

            print("error...........")

        }

    }

    //f

    func creatSocketToConnectServer(data:NSData,tag:Int) ->Void{

        do{

            self.socketTag= tag

            self.mSocket.send(dataasData, toHost:Home_ip, port:home_port, withTimeout:home_timeout, tag: tag)

        }

    }

}

// MARK: - GCDAsyncSocketDelegate

extension MySocket : GCDAsyncUdpSocketDelegate {

    public func udpSocket(_sock:GCDAsyncUdpSocket, didReceive data:Data, fromAddress address:Data, withFilterContext filterContext:Any?) {

        self.delegate?.mySocketData(data: [UInt8](data), tag:self.socketTag)

    }

    public func udpSocket(_sock:GCDAsyncUdpSocket, didNotConnect error:Error?) {

        warningTIps(waringStr:"连接失败!")

    }

    public func udpSocket(_sock:GCDAsyncUdpSocket, didSendDataWithTag tag:Int) {

        print("已经发送数据。。。。")

    }

    public func udpSocketDidClose(_sock:GCDAsyncUdpSocket, withError error:Error?) {

        warningTIps(waringStr:"连接已经断开!")

    }

    public func udpSocket(_sock:GCDAsyncUdpSocket, didConnectToAddress address:Data) {

        print("开始链接")

    }

}

//---------/初始化

var mySocket:MySocket?

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

    varwindow:UIWindow?

    func application(_application:UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey:Any]?) ->Bool{

         mySocket = MySocket()

}

相关文章

网友评论

      本文标题:CocoaAsyncSocket使用(Swift4)

      本文链接:https://www.haomeiwen.com/subject/gexfzftx.html