How to use NWConnection in order to send messages using TCP?

In order to give Network framework a try, i started a test project. A simple Server-Client communication. TCP connection is established well. Now i'm trying to send a series of short independent messages - and this is where i'm completely stuck.

After first message, server is sending strings made of natural numbers from 1 to 999. Each number is sent as separate Data, isComplete and contentContext default values are true and .defaultMessage correspondingly.
Code Block var count = 0
func send(data: Data) {
self.connection.send(content: data, completion: .contentProcessed( { error in
if let error = error {
self.connectionDidFail(error: error)
return
}
self.count += 1
let newData = "\(self.count)".data(using: .utf8)!
if self.count < 1000 {
self.send(data: newData)
}
print("connection \(self.id) did send, data: \(newData as NSData)")
}))
}


Client is receiving them...
Code Block private func setupReceive() {
nwConnection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { (data, contentContext, isComplete, error) in
if let data = data, !data.isEmpty {
print("isComplete: \(isComplete)")
print("isFinal: \(contentContext.isFinal)")
let message = String(data: data, encoding: .utf8)
print("connection did receive, data: \(data as NSData) string: \(message ?? "-" )")
}
if let error = error {
self.connectionDidFail(error: error)
} else {
self.setupReceive()
}
}
}

... but there is something wrong. Some messages look like their bytes are stuck together (for example consecutive messages "2", "3", "4", "5" could be received like a single message "2345")
For all received messages isComplete equals false and contentContext property isFinal equals true, while .defaultMessage.isFinal should be equal to false.
As i said, for now i'm stuck. The docs are kinda ambiguous, and most of examples from the Internet are about UDP, not TCP.

How can one send a series of separate messages?

How can one send a series of separate messages?

It looks like you are continuously sending data on the connection from the server without ever marking it complete. Also, on the client you are reading anywhere from 1 to 65536 bytes, which is fine, but could allow you to receive 4, 20, or 10 bytes when these bytes are ready on the client connection.

Checkout Building a Custom Peer-to-Peer Protocol that demonstrates creating a TCP framer and reading specific frame lengths from the connection. It's a great example.


Matt Eaton
DTS Engineering, CoreOS
meaton3@apple.com
How to use NWConnection in order to send messages using TCP?
 
 
Q