Last active
November 9, 2022 22:25
-
-
Save godrm/c72acba2a999b0bd33f0c1e9a300ebad to your computer and use it in GitHub Desktop.
EchoServer with Network.Framework
This file contains hidden or 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
// | |
// EchoServer.swift | |
// CS16 | |
// | |
// Created by JK on 2020/01/14. | |
// Copyright © 2020 codesquad. All rights reserved. | |
// | |
import Foundation | |
import Network | |
class EchoServer { | |
let networkQueue = DispatchQueue.init(label: "myqueue.codesquad.kr") | |
var listener : NWListener | |
init?(with port: NWEndpoint.Port) { | |
let options = NWProtocolTCP.Options() | |
let params = NWParameters.init(tls: .none, tcp: options) | |
params.allowLocalEndpointReuse = true | |
let binding = try? NWListener(using: params, on: port) | |
guard binding != nil else { return nil } | |
listener = binding! | |
} | |
func run() { | |
setupListener() | |
} | |
private func setupListener() { | |
listener.stateUpdateHandler = { newState in | |
switch newState { | |
case .ready: | |
print("Listener ready on \(String(describing: self.listener.port))") | |
case .failed(let error): | |
print("Listener failed with \(error), restarting") | |
self.listener.cancel() | |
default: | |
break | |
} | |
} | |
listener.newConnectionHandler = setup(connection:) | |
listener.start(queue: networkQueue) | |
} | |
private func setup(connection: NWConnection) { | |
connection.stateUpdateHandler = { newState in | |
switch newState { | |
case .ready: | |
self.setupReceiver(of: connection) | |
case .failed(_): | |
connection.cancel() | |
case .cancelled: | |
print("\(connection) cancelled") | |
default: | |
break | |
} | |
} | |
connection.start(queue: self.networkQueue) | |
} | |
private func setupReceiver(of connection: NWConnection) { | |
connection.receive(minimumIncompleteLength: 4, maximumLength: 1024) { (content, context, isComplete, error) in | |
if let data = content, !data.isEmpty { | |
connection.send(content: content, completion: .idempotent) | |
print("\(connection) received and echo - ", String(data: data, encoding: .utf8)!) | |
} | |
connection.forceCancel() | |
if let error = error { | |
print("\(connection) error - ", error.localizedDescription) | |
} | |
} | |
} | |
} |
This file contains hidden or 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 | |
let server = EchoServer(with: NWEndpoint.Port.init(integerLiteral: 9000)) | |
server?.run() | |
RunLoop.main.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment