I want to see Apple’s TCP sample code, When I saw Apple’s UDP sample code - UDPEcho. But I does’t found it.
Do you know Apple’s TCP sample code like UDPEcho?
I want to see Apple’s TCP sample code …
Apple platforms support many different TCP APIs. The TCPTransports sample code shows four of thsee APIs (
CFSocketStream
,
NSURLSessionStreamTask
, BSD Sockets, and
NWTCPConnection
).
The only remaining API is the Network framework, for which there isn’t a good official sample yet [1]. We are working on addressing that, but for the moment, I’ve pasted a tiny example in below, just to get your started.
If you have any further questions about any of these APIs, I’m happy to answer them.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"
[1] There’s nwcat, but it has a number of drawbacks, not least of which is that it’s a C sample.
import Foundation
import Network
class Main {
init(hostName: String, port: Int) {
let host = NWEndpoint.Host(hostName)
let port = NWEndpoint.Port("\(port)")!
self.connection = NWConnection(host: host, port: port, using: .tcp)
}
let connection: NWConnection
func start() {
NSLog("will start")
self.connection.stateUpdateHandler = self.didChange(state:)
self.startReceive()
self.connection.start(queue: .main)
}
func stop() {
self.connection.cancel()
NSLog("did stop")
}
private func didChange(state: NWConnection.State) {
switch state {
case .setup:
break
case .waiting(let error):
NSLog("is waiting: %@", "\(error)")
case .preparing:
break
case .ready:
break
case .failed(let error):
NSLog("did fail, error: %@", "\(error)")
self.stop()
case .cancelled:
NSLog("was cancelled")
self.stop()
@unknown default:
break
}
}
private func startReceive() {
self.connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { data, _, isDone, error in
if let data = data, !data.isEmpty {
NSLog("did receive, data: %@", data as NSData)
}
if let error = error {
NSLog("did receive, error: %@", "\(error)")
self.stop()
return
}
if isDone {
NSLog("did receive, EOF")
self.stop()
return
}
self.startReceive()
}
}
func send(line: String) {
let data = Data("\(line)\r\n".utf8)
self.connection.send(content: data, completion: NWConnection.SendCompletion.contentProcessed { error in
if let error = error {
NSLog("did send, error: %@", "\(error)")
self.stop()
} else {
NSLog("did send, data: %@", data as NSData)
}
})
}
static func run() -> Never {
let m = Main(hostName: "127.0.0.1", port: 12345)
m.start()
let t = DispatchSource.makeTimerSource(queue: .main)
var counter = 99
t.setEventHandler {
m.send(line: "\(counter) bottles of beer on the wall.")
counter -= 1
if counter == 0 {
m.stop()
exit(EXIT_SUCCESS)
}
}
t.schedule(wallDeadline: .now() + 1.0, repeating: 1.0)
t.activate()
dispatchMain()
}
}
Main.run()