/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import Network protocol NetworkServerDelegate: AnyObject { func serverBecameReady() func connectionOpened(id: Int) func connectionReceivedData(id: Int, data: Data) } class NetworkServer: NetworkConnectionDelegate { weak var delegate: NetworkServerDelegate? let listener: NWListener private var serverQueue: DispatchQueue? private var connectionsByID: [Int: NetworkConnection] = [:] init() { self.listener = try! NWListener(using: .tcp, on: 12345) } init(name: String?, type: String, domain: String?, txtRecord: NWTXTRecord) { self.listener = try! NWListener(using: .tcp, on: 0) self.listener.service = NWListener.Service(name: name, type: type, domain: domain, txtRecord: txtRecord) } func start(queue: DispatchQueue) throws { self.serverQueue = queue self.listener.stateUpdateHandler = self.onStateDidChange(to:) self.listener.newConnectionHandler = self.onNewConnectionAccepted(nwConnection:) self.listener.start(queue: queue) } func onStateDidChange(to newState: NWListener.State) { switch newState { case .setup: break case .waiting: break case .ready: self.delegate?.serverBecameReady() break case .failed(let error): print("server did fail, error: \(error)") self.stop() case .cancelled: break default: break } } private func onNewConnectionAccepted(nwConnection: NWConnection) { let connection = NetworkConnection(nwConnection: nwConnection) self.connectionsByID[connection.id] = connection connection.delegate = self connection.start(queue: self.serverQueue!) log.info("Server accepted connection \(connection)") } private func stop() { self.listener.stateUpdateHandler = nil self.listener.newConnectionHandler = nil self.listener.cancel() closeAllConnections() } private func heartbeat() { let timestamp = Date() print("server heartbeat, timestamp: \(timestamp)") for connection in self.connectionsByID.values { let data = "heartbeat, connection: \(connection.id), timestamp: \(timestamp)\r\n" connection.send(data: Data(data.utf8)) } } func closeAllConnections() { for connection in self.connectionsByID.values{ connection.close() } // Theoretically next call shouldn't have to remove anything as the connections // removed them selves by calling our connectionClosed function self.connectionsByID.removeAll() } func sendToAll(data: Data) { for conn in self.connectionsByID { conn.value.send(data: data) } } func sendTo(id: Int, data: Data) { self.connectionsByID[id]?.send(data: data) } func sendToAllExcept(id: Int, data: Data) { for conn in self.connectionsByID { if (conn.value.id != id) { conn.value.send(data: data) } } } var port: NWEndpoint.Port? { get { return self.listener.port } } // MARK: NetworkConnectionDelegate func connectionOpened(connection: NetworkConnection) { log.info("Server connection opened") self.delegate?.connectionOpened(id: connection.id) } func connectionClosed(connection: NetworkConnection) { self.connectionsByID.removeValue(forKey: connection.id) log.info("Server connection closed (\(connection))") } func connectionError(connection: NetworkConnection, error: Error) { log.error("Server connection error: \(error) (\(connection))") } func connectionReceivedData(connection: NetworkConnection, data: Data) { self.delegate?.connectionReceivedData(id: connection.id, data: data) } }