Created
December 11, 2024 14:38
-
-
Save majek/cb54b537c74506164d2a7fa2d6601491 to your computer and use it in GitHub Desktop.
MPTCP Network.framework example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import Network | |
func sendAndReceiveData(connection: NWConnection) { | |
let data = "Hello, server!".data(using: .utf8) | |
connection.send(content: data, completion: .contentProcessed({ error in | |
if let error = error { | |
print("Failed to send data: \(error)") | |
} else { | |
print("Message sent successfully") | |
} | |
})) | |
receiveData(connection: connection) | |
} | |
func receiveData(connection: NWConnection) { | |
connection.receive(minimumIncompleteLength: 1, maximumLength: 1024) { data, context, isComplete, error in | |
if let data = data, !data.isEmpty { | |
let message = String(data: data, encoding: .utf8) ?? "Invalid UTF-8 data" | |
print("Received: \(message)") | |
} else if let error = error { | |
print("Receive failed: \(error)") | |
return | |
} | |
receiveData(connection: connection) | |
} | |
} | |
func createInteractiveConnection(ip: String, port: UInt16) { | |
let host = NWEndpoint.Host(ip) | |
let endpointPort = NWEndpoint.Port(rawValue: port)! | |
let parameters = NWParameters.tcp | |
parameters.multipathServiceType = .interactive | |
let connection = NWConnection(host: host, port: endpointPort, using: parameters) | |
connection.start(queue: .main) | |
connection.stateUpdateHandler = { state in | |
switch state { | |
case .ready: | |
print("Connection established to \(ip):\(port)") | |
sendAndReceiveData(connection: connection) | |
case .failed(let error): | |
print("Connection failed: \(error)") | |
default: | |
break | |
} | |
} | |
dispatchMain() | |
} | |
let args = CommandLine.arguments | |
let (ip, port) = (args[1], UInt16(args[2])!) | |
createInteractiveConnection(ip: ip, port: port) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment