MatterGoal
MatterGoal

Reputation: 16430

Sending bytes on outputstream with Swift

I'm working with a custom network protocol that requires a precise bytes sequence to do a sort of handshake, as example the first call should send a body like:

0003joy that, translated in a [UInt8] should be [0x00,0x00,0x00,0x03,0x6a,0x6f,0x79] (please note that the first 4 numbers should not be converted to char... I'm sending the numeric value, as per protocol request)

I'm trying to send this sequence to an outputstream but I'm wondering if the steps I'm following are correct, here is my code... do you see anything strange that might prevent this sequence to reach the server?

// Create Bytes sequence
let bytes:[UInt8] = [0x00,0x00,0x00,0x03,0x6a,0x6f,0x79]

// Convert Bytes array do Data
let dt = Data(bytes)

// Send Data to stream 
_ = dt.withUnsafeBytes {
    guard let pointer = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
        return
    }
    outputStream.write(pointer, maxLength: dt.count)
}

Also, do I need to convert the bytes sequence to Data? is there a way to send bytes sequence directly into the socket without converting it into Data?

Upvotes: 1

Views: 817

Answers (1)

Sulthan
Sulthan

Reputation: 130102

I don't see anything wrong with your code but the conversion to Data is not needed:

bytes.withUnsafeBytes {
    guard let pointer = $0.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
        return
    }
    outputStream.write(pointer, maxLength: bytes.count)
}

since [UInt8] conforms to ContiguousBytes.

Actually, the following is also possible:

bytes.withUnsafeBufferPointer {
    guard let baseAddress = $0.baseAddress else { return }
    outputStream.write(baseAddress, maxLength: bytes.count)
}

Upvotes: 1

Related Questions