Swift基于CocoaAsyncSocket开发Socket通信

2018-06-13 16:41:41 浏览数 (1)

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

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

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

添加CocoaAsyncSocket
代码语言:javascript复制
 import CocoaAsyncSocket
添加代理
代码语言:javascript复制
class SESocketManager: NSObject, GCDAsyncSocketDelegate  {

}
初始化与长连接建立
代码语言:javascript复制
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")
    }
}
长连接建立成功后代理回调
代码语言:javascript复制
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) -> Void {
    print("Successful")
    socketDidConnectCreatLogin()
    socketDidConnectBeginSendBeat()
}
建立连接成功后向服务器检验登录与发送心跳包
代码语言:javascript复制
   // 长连接建立后 开始与服务器校验登录
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)
}
向服务器发送数据
代码语言:javascript复制
 // 向服务器发送数据
func socketWriteDataToServer(body: Dictionary<String, Any>) {
    // 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)
}
发送与接收数据代理回调
代码语言:javascript复制
 // 服务器接收到数据 -->> 接收到数据后抛出去
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, 带有语法错误请谅解

0 人点赞