Swift
Swift
Receive a 4-byte Length Prefix from a Socket
See more Socket/SSL/TLS Examples
Demonstrates Socket.ReceiveCount, which reads a four-byte length prefix as a signed 32-bit integer. A return value of -1 indicates failure.
Background. Reading the length prefix first tells the application exactly how many bytes to read for the message body, which is a reliable way to know when a full message has arrived.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
let socket = CkoSocket()!
// Connect to the server using TLS.
var bTls: Bool = true
var maxWaitMs: Int = 5000
success = socket.connect(hostname: "example.com", port: 5000, ssl: bTls, maxWaitMs: maxWaitMs)
if success == false {
print("\(socket.lastErrorText!)")
return
}
// Read a four-byte length prefix as a signed 32-bit integer (network byte order by default). A
// return value of -1 indicates failure.
var messageLength: Int = socket.receiveCount().intValue
if messageLength < 0 {
print("\(socket.lastErrorText!)")
return
}
print("The peer will send \(messageLength) bytes.")
}