I'm using peer-to-peer and I successfully connect one client to another but when I send the echo to the individual connection the receiving client doesn't get a response.
Initial send
let data = NYKeyedArchiver....
let message = NWProtocolWebSocket.Metadata(opcode: .text)
let context = NWConnection.ContentContext(identifier: "send",
metadata: [message])
connection.send(content: data, contentContext: context, isComplete: true, completion: .contentProcessed({ (error) in
if let error = error { return }
print("Sent")
}))
Receive data and send Echo response
func receivedIncoming(connection) {
connection.receive(minimumIncompleteLength: 1, maximumLength: 65535) { (data, context, isComplete, error) in
if let err = error {
print(err) // never gets hit
return
}
if let data = data, !data.isEmpty {
// do something with data
if let color = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? UIColor {
// this should only run on the other device once echo is received after 5 secs
self?.view.backgroundColor = color
}
let randomColor = UIColor.random // func create random color
let colorData = randomColor.encode() // func encode color to data
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
connection.send(content: colorData, completion : .idempotent)
// I've also tried
let message = NWProtocolWebSocket.Metadata(opcode: .text)
let context = NWConnection.ContentContext(identifier: "send", metadata: [message])
connection.send(content: colorData, contentContext: context, isComplete: true, completion: .contentProcessed({ (error) in
if let error = error { return }
print("Color data sent") // this always prints
}))
}
} else {
print("data is empty") // never gets hit
}
}
}
NWConnection
weak var delegate: PeerConnectionDelegate?
var connection: NWConnection?
// Outgoing Connection
init(endPoint: NWEndpoint, delegate: PeerConnectionDelegate) {
self.delegate = delegate
let tcpOptions = NWProtocolTCP.Options()
tcpOptions.enableKeepalive = true
tcpOptions.keepaliveIdle = 2
let parameters = NWParameters(tls: nil, tcp: tcpOptions)
parameters.includePeerToPeer = true
parameters.allowLocalEndpointReuse = true
connection = NWConnection(to: endPoint, using: parameters)
startOutgoingConnection()
}
// Incoming Connection
init(connection: NWConnection, delegate: PeerConnectionDelegate) {
self.delegate = delegate
self.connection = connection
startIncomingConnection()
}
func startIncomingConnection() {
connection?.stateUpdateHandler = { (nwConnectionState) in
case .ready:
self.delegate?.receivedIncoming(connection)
// ...
}
Why is the echo data being sent but not received?
8
0
1.8k