Swift基于CocoaAsyncSocket开发Socket通信

首先我们以实现方式来切入,基本上有以下四种实现方式:

https://github.com/zhangrongwu/Swift-IM.git

基于Scoket原生:代表框架 CocoaAsyncSocket。
基于WebScoket:代表框架 SocketRocket。
基于MQTT:代表框架 MQTTKit。
基于XMPP:代表框架 XMPPFramework。

添加CocoaAsyncSocket

 import CocoaAsyncSocket

添加代理

class SESocketManager: NSObject, GCDAsyncSocketDelegate  {

}

初始化与长连接建立

var clientSocket:GCDAsyncSocket!

override init() {
    super.init()
    clientSocket = GCDAsyncSocket()
    clientSocket.delegate = self
    clientSocket.delegateQueue = DispatchQueue.main
    creatSocketToConnectServer()
}

 // 创建长连接
func creatSocketToConnectServer() -> Void {
    do {
        connectStatus = 0
        try  clientSocket.connect(toHost: kConnectorHost, onPort: UInt16(kConnectorPort), withTimeout: TimeInterval(timeOut))
    } catch {
        print("conncet error")
    }
}

长连接建立成功后代理回调

func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) -> Void {
    print("Successful")
    socketDidConnectCreatLogin()
    socketDidConnectBeginSendBeat()
}

建立连接成功后向服务器检验登录与发送心跳包

   // 长连接建立后 开始与服务器校验登录
func socketDidConnectCreatLogin() -> Void {
    let login = ["c":"1","p":"ca5542d60da951afeb3a8bc5152211a7","d":"dev_"]
    socketWriteDataToServer(body: login)
    reconnectionCount = 0
    connectStatus = 1
    reconncetStatusHandle?(true)
    delegate?.reconnectionSuccess()
    guard let timer = self.reconnectTimer else {
        return
    }
    timer.invalidate()
}

// 长连接建立后 开始发送心跳包
func socketDidConnectBeginSendBeat() -> Void {
    beatTimer = Timer.scheduledTimer(timeInterval: TimeInterval(heartBeatTimeinterval),
                                     target: self,
                                     selector: #selector(sendBeat),
                                     userInfo: nil,
                                     repeats: true)
    RunLoop.current.add(beatTimer, forMode: RunLoopMode.commonModes)
}

// 向服务器发送心跳包
func sendBeat() {
    let beat = ["c":"3"]
    socketWriteDataToServer(body:beat)
}

向服务器发送数据

 // 向服务器发送数据
func socketWriteDataToServer(body: Dictionary) {
    // 1: do   2: try?    3: try!
    guard let data:Data = try? Data(JSONSerialization.data(withJSONObject: body,
                                                           options: JSONSerialization.WritingOptions(rawValue: 1))) else { return }
    print(body)
    clientSocket.write(data, withTimeout: -1, tag: 0)
    clientSocket.readData(to: GCDAsyncSocket.crlfData(), withTimeout: -1, tag: 0)
}

发送与接收数据代理回调

 // 服务器接收到数据 -->> 接收到数据后抛出去
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) -> Void {
    clientSocket.write(data, withTimeout: -1, tag: 0)
    clientSocket.readData(to: GCDAsyncSocket.crlfData(), withTimeout: -1, tag: 0)
    socketDidReadData(data: data, tag: tag)
}


func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) -> Void {
    clientSocket.readData(to: GCDAsyncSocket.crlfData(), withTimeout: -1, tag: 0)
}

// 断开连接
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) -> Void {
    socketDidDisconectBeginSendReconnect()
}

刚上手Swift, 带有语法错误请谅解

你可能感兴趣的:(Swift基于CocoaAsyncSocket开发Socket通信)