CocoaAsyncSocket 通信

关飞翼
2023-12-01

所有资源来自github

swift socket资源

  • socketio/socket.io-client-swift

  • swiftsocket/SwiftSocket

  • AlwaysRightInstitute/SwiftSockets

由于各种问题,我不知道什么问题,反正各种问题各种换最终选择了:

CocoaAsyncSocket

github地址  https://github.com/robbiehanson/CocoaAsyncSocket

使用总结:

1、下载 AsyncSocket

2、导入 CFNetwork.framework

3、实现 AsyncSocketDelegate


关键代码,创建socket客户端,连接服务器

var socket:AsyncSocket!
socket = AsyncSocket(delegate: self)
try! socket.connectToHost(tcpip, onPort: tcpport , withTimeout: intervalEnum.connect.rawValue)
socket.setRunLoopModes([NSRunLoopCommonModes])

重写代理中的方法,添加心跳

func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
        print("didConnectToHost \(host) \(port)")
        sock.readDataWithTimeout(intervalEnum.read.rawValue, tag: tagEnum.heart.hashValue)
        
        timer = NSTimer.scheduledTimerWithTimeInterval(intervalEnum.timer.rawValue, target: self, selector: "timerAction:", userInfo: nil, repeats: true)
        timer.fire()
    }

心跳实现及数据发送

func timerAction(sender:AnyObject?){
        print("timerAction")        
        let long = "我是心跳\n"
        let data = long.dataUsingEncoding(NSUTF8StringEncoding)
        socket.writeData(data, withTimeout: intervalEnum.write.rawValue, tag: tagEnum.heart.hashValue)   
    }

读取数据

    func onSocket(sock: AsyncSocket!, didWriteDataWithTag tag: Int) {
        print("didWriteDataWithTag \(tag)")
        
        sock.readDataWithTimeout(intervalEnum.read.rawValue, tag: tagEnum.heart.hashValue)
    }
    
    func onSocket(sock: AsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
        let str = NSString(data: data, encoding: NSUTF8StringEncoding)
        print("didReadData \(tag) \(str)")
        
        sock.readDataWithTimeout(intervalEnum.read.rawValue, tag: tagEnum.heart.hashValue)
    }

其中各种关系好没有理清楚,先总结下

转载于:https://my.oschina.net/asjoker/blog/551112

 类似资料: