美文网首页
Socket tips

Socket tips

作者: ShawnDu | 来源:发表于2016-03-09 22:40 被阅读57次

    封装消息

    /*
                 * 消息格式:
                 * 
                 *  0 1 2 3 4 ... Length
                 * +-------+------------+
                 * |Length | Payload    |
                 * +-------+------------+
                 *
     */
    messageData = NSMutableData(capacity: Int(totalLength))
    messageData?.appendBytes(&totalLength, length: sizeof(UInt32.self))
    messageData?.appendData(payload)
    

    最简单的消息,header+payload, header中只含有payload的长度,在往消息data上append数据时,对于一个UInt32,用appendBytes;payload可以用一个字典,序列化成data,直接appendData。

    往Stream中写数据

    func writeData(data: NSData, toStream stream: NSOutputStream, startingAtOffset offset: Int) -> Int {
        var written = 0
        var currentOffset = offset
        while stream.hasSpaceAvailable && currentOffset < data.length {
            let writeResult = stream.write(UnsafePointer<UInt8>(data.bytes) + currentOffset, maxLength: data.length - currentOffset)
            guard writeResult >= 0 else { return writeResult }
            written += writeResult
            currentOffset += writeResult
        }
        return written
    }
    

    把Socket地址转化成String

    func saToString(sa: UnsafePointer<sockaddr>) -> String? {
        var hostBuffer = [CChar](count: Int(NI_MAXHOST), repeatedValue:0)
        var portBuffer = [CChar](count: Int(NI_MAXSERV), repeatedValue:0)
        guard getnameinfo(sa, socklen_t(sa.memory.sa_len), &hostBuffer, socklen_t(hostBuffer.count), &portBuffer, socklen_t(portBuffer.count), NI_NUMERICHOST | NI_NUMERICSERV) == 0
            else { return nil }
        return String.fromCString(hostBuffer)
    }
    

    先把数据读到buffer中,再调用系统的函数getnameinfo().

    微信公众号

    开发者思维 devthinking

    相关文章

      网友评论

          本文标题:Socket tips

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