CocoaAsyncSocket (二): GCDAsyncSocketDelegate

2. 通过GCDAsyncSocketDelegate实现 tcp 通讯

import Foundation

// tcp delegate
class GCDAsynTcpSocketDelegate: NSObject, GCDAsyncSocketDelegate {
    var tcpSocket: GCDAsyncSocket?
    // 服务器的 IP
    var serverHost: String!
    // Tcp 端口
    var tcpPort: UInt16 = tcpServerPort

    override init() {
        super.init()
        setupConnection()
    }

    func initialize(serverHost: String, tcpPort: UInt16) {
        self.serverHost = serverHost
        self.tcpPort = tcpPort
        var error: NSError?

        if let isConnected = tcpSocket?.connectToHost(serverHost, onPort: tcpPort, error: &error) {
            if isConnected {
                logger.debug("connectToHost:\(self.serverHost):\(self.tcpPort) success!")
            }else {
                tcpSocket?.disconnect()
                logger.debug("connectToHost:\(self.serverHost):\(self.tcpPort) error:\(error)!")
            }
        }else {
            tcpSocket?.disconnect()
            logger.debug("connectToHost:\(self.serverHost):\(self.tcpPort) failed!")
        }

    }

    // tcp Client
    // 初始化 tcp 对象
    func setupConnection() {
        tcpSocket = GCDAsyncSocket(delegate: self, delegateQueue: dispatch_get_main_queue())
    }

    // 发送数据
    func send(message: String) {
        let messageData = message.dataUsingEncoding(NSUTF8StringEncoding)
        tcpSocket?.writeData(messageData, withTimeout: socketTimeOut, tag: 0)
        tcpSocket?.readDataWithTimeout(socketTimeOut, tag: 0)
    }


    // 需要实现的GCDAsyncSocketDelegate方法
    // - (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port;
    func socket(socket : GCDAsyncSocket, didConnectToHost host:String, port p:UInt16) {
        logger.debug("didConnectToHost: \(host):\(p)")
    }

    // - (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;
    func socket(socket : GCDAsyncSocket, didReadData data:NSData, withTag tag:Int) {
        let receivedString = NSString(data: data, encoding: NSUTF8StringEncoding)
        logger.debug("didReadData:\(receivedString)")
    }
}

问题记录

  1. 并没有遇到传说中因为__weak id delegate; 导致的无法连接服务器的问题
    http://m.blog.csdn.net/blog/wjz311/42619995
    http://stackoverflow.com/questions/26920250/gcdasyncsocket-on-browser-connects-and-disconnects-immediately-with-socket-clos

  2. 只能发送不能接收数据的问题

    // 发送数据
    func send(message: String) {
        let messageData = message.dataUsingEncoding(NSUTF8StringEncoding)
        tcpSocket?.writeData(messageData, withTimeout: socketTimeOut, tag: 0)
        // 少了readDataWithTimeout的调用
        tcpSocket?.readDataWithTimeout(socketTimeOut, tag: 0)
    }
2015-06-28 15:06126